This Blog is created and maintained for personal use. If any of these posts are useful to other, then i am very happy. Please share your thoughts and ideas to improve this blog.
Wednesday, November 2, 2011
Thursday, October 27, 2011
GRIDVIEW EVENTS IN ASP.NET with C#
GridView is the most reused tool in ASP.NET. This gridview contains 7 major events which are always used in every situation.
Code Behind
<asp:GridView ID="grdGroups" runat="server" AutoGenerateColumns="false"
CssClass="GridStyle" AllowPaging="True"
onpageindexchanging="grdGroups_PageIndexChanging"
onrowcancelingedit="grdGroups_RowCancelingEdit"
onrowdeleting="grdGroups_RowDeleting" onrowediting="grdGroups_RowEditing"
onrowupdating="grdGroups_RowUpdating" PageSize="5" Width="70%"
onrowcommand="grdGroups_RowCommand" onsorting="grdGroups_Sorting" AllowSorting="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GroupName" HeaderStyle-Width="250px" SortExpression="groupname">
<ItemTemplate>
<%#Eval("groupname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgroupName" runat="server" CssClass="controlStyle" Text='<%#Eval("groupname")%>' MaxLength="20">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="! Enter group Name" ControlToValidate="txtgroupName" ValidationGroup="G" Text="!!">
</asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="150px" SortExpression="GroupID">
<ItemTemplate>
<asp:LinkButton ID="lnkGroupEdit" runat="server" CommandName="Edit" ToolTip="Edit this Group"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkGroupUpdate" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Update"
Text="Update" ValidationGroup="G" ToolTip="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false" ValidationGroup="G"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkGroupDelete" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Delete" Text="Delete"
ToolTip="Delete this Group" OnClientClick="javascript:return confirm('If you delete this Group, all Contacts of this Group Also Deleted,Are you sure you want to delete this Item?');"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle CssClass="GridAlter" />
<RowStyle CssClass="gridrowstyle" />
<PagerStyle CssClass="GridPager" />
</asp:GridView>
- grdGroups_PageIndexChanging
- grdGroups_RowDeleting
- grdGroups_RowEditing
- grdGroups_RowCancelingEdit
- grdGroups_RowUpdating
- grdGroups_RowCommand
- grdGroups_Sorting
All the above events are web server events which are coded as below
//This PageIndexChanging event is used for navigating from one page to another page. Here page means set //of records. Each page contains count of records. The page size is defined in code behind.
protected void grdGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdGroups.PageIndex = e.NewPageIndex;
GetGroups();
}
catch (Exception ex)
{
Throw ex;
}
}
//This RowDeleting Event is used for deleting a single record at a time.
protected void grdGroups_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
objGrp.GroupID = Convert.ToInt32(Session["GroupID"].ToString());
objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
objGrp.DeleteGroup();// This method contains original logic for deleting the record.
GetGroups();
}
catch (Exception ex)
{
Throw ex;
}
}
//RowEditing Event is used for setting up the selected record in edit mode.
protected void grdGroups_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
grdGroups.EditIndex = e.NewEditIndex;
GetGroups();
}
catch (Exception ex)
{
Throw ex;
}
}
//CancelEdit Event is used for reset the selected record from edit mode.
protected void grdGroups_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
try
{
grdGroups.EditIndex = -1;
GetGroups();
}
catch (Exception ex)
{
Throw ex;
}
}
//After Edit the selected record values, this RowUpdating Event is used to update the edited values.
protected void grdGroups_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txt = (TextBox)grdGroups.Rows[e.RowIndex].FindControl("txtgroupName");
grdGroups.EditIndex = -1;
objGrp.GroupName = txt.Text.Trim();
objGrp.GroupID = Convert.ToInt32(Session["GroupID"].ToString());
objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
objGrp.UpdateGroup(); // This method contains original logic to update the record on database.
GetGroups();
}
catch (Exception ex)
{
Throw ex;
}
}
//This event is used for external purposes like button click events inside a grid.
protected void grdGroups_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.ToString() == "Update")
{
Session["GroupID"] = e.CommandArgument.ToString();
}
if (e.CommandName.ToString() == "Delete")
{
Session["GroupID"] = e.CommandArgument.ToString();
}
}
catch (Exception ex)
{
throw ex;
}
}
//Row_Sorting Event is used for sorting the record by selecting the column.
protected void grdGroups_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
DataTable dt = ((DataSet)ViewState["GroupList"]).Tables[0];
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
grdGroups.DataSource = dt;
grdGroups.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
private void GetGroups()
{
try
{
objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
DataSet ds = objGrp.GetGroupsbyUser();
ViewState["GroupList"] = ds;
if (ds.Tables[0].Rows.Count > 0)
{
grdGroups.DataSource = ds.Tables[0];
grdGroups.DataBind();
}
else
{
// Below code is used for displaying some text if there is no record to bind to grid.
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdGroups.DataSource = ds;
grdGroups.DataBind();
int columnscount = grdGroups.Columns.Count;
grdGroups.Rows[0].Cells.Clear();
grdGroups.Rows[0].Cells.Add(new TableCell());
grdGroups.Rows[0].Cells[0].ColumnSpan = columnscount;
grdGroups.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
grdGroups.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
grdGroups.Rows[0].Cells[0].Font.Bold = true;
grdGroups.Rows[0].Cells[0].Text = "No Groups List";
}
}
catch (Exception ex)
{
Throw ex;
}
}
//This method is used in Row_Sorting Event.
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
Code Behind
<asp:GridView ID="grdGroups" runat="server" AutoGenerateColumns="false"
CssClass="GridStyle" AllowPaging="True"
onpageindexchanging="grdGroups_PageIndexChanging"
onrowcancelingedit="grdGroups_RowCancelingEdit"
onrowdeleting="grdGroups_RowDeleting" onrowediting="grdGroups_RowEditing"
onrowupdating="grdGroups_RowUpdating" PageSize="5" Width="70%"
onrowcommand="grdGroups_RowCommand" onsorting="grdGroups_Sorting" AllowSorting="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GroupName" HeaderStyle-Width="250px" SortExpression="groupname">
<ItemTemplate>
<%#Eval("groupname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgroupName" runat="server" CssClass="controlStyle" Text='<%#Eval("groupname")%>' MaxLength="20">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="! Enter group Name" ControlToValidate="txtgroupName" ValidationGroup="G" Text="!!">
</asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="150px" SortExpression="GroupID">
<ItemTemplate>
<asp:LinkButton ID="lnkGroupEdit" runat="server" CommandName="Edit" ToolTip="Edit this Group"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkGroupUpdate" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Update"
Text="Update" ValidationGroup="G" ToolTip="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false" ValidationGroup="G"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkGroupDelete" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Delete" Text="Delete"
ToolTip="Delete this Group" OnClientClick="javascript:return confirm('If you delete this Group, all Contacts of this Group Also Deleted,Are you sure you want to delete this Item?');"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="GridHeader" />
<AlternatingRowStyle CssClass="GridAlter" />
<RowStyle CssClass="gridrowstyle" />
<PagerStyle CssClass="GridPager" />
</asp:GridView>
Tuesday, October 18, 2011
Thursday, September 29, 2011
Thursday, September 8, 2011
HOW TO OPEN POPUP USING JAVASCRIPT
<a href="#" onclick="OpenWindow()">Insert Data<script language="javascript" type="text/javascript">
function OpenWindow()
{
window.open ("PopUpWindow.aspx",
"mywindow", "menubar=0,resizable=0," +
"width=350,height=250,toolbars=0");
}
</script>
Thursday, August 18, 2011
Thursday, August 11, 2011
Set status bar text using asp.net
protected void Page_Load(object sender, EventArgs e)
{
// Create a message string
string strMessage = "This is a message in status bar";
// Register startup script to show a message in status bar
this.RegisterStartupScript("SetStatusText", "<script>window.status='" +
strMessage + "';</script>");
}
How to prevent visiting pages from History after Logout
After having successfully logged-in to an application, you are redirected to the next page (say Home.aspx) which is a content page of master page (say Master.master). In this master page you have a link for logout. When you click on the logout button it redirects you to the Login page (provided this is not the content page of Master.master). Now if you click on the back arrow of browser then it goes to the previous page. To avoid this, the following code can be used in your master page where the logout button is present. |
Design a login page, give user name and password then redirect to some other page which is a content page of a Master page. In this master page one link button should be present for logout. When you click on the logout button it redirects to the login page. Then when you click on the back arrow of the browser it again goes to the previous page (that you already visit before logout). Even if you write code for session clear in logout button click event still it goes to previous page. To avoid this write few lines of code in Page_Init method of master page. protected void Page_Init(object sender, EventArgs e){ Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); } Master.master <asp:LinkButton ID="lnkLogout" runat="server" Text="logout"onclick="lnkLogout_Click"></asp:LinkButton> Master.master.cs protected void Page_Init(object sender, EventArgs e){ Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); } protected void Page_Load(object sender, EventArgs e) { long userId = Convert.ToInt64(Session["UserId"]); if(!IsPostBack) { if(userId == 0) { Response.Redirect("Login.aspx"); } } } protected void lnkLogout_Click(object sender, EventArgs e) { Session.Clear(); Session.Abandon(); Response.Redirect("Login.aspx"); |
Wednesday, August 10, 2011
Tuesday, July 26, 2011
HOW to Install/Uninstall Windows Service
To Install a Windows Service, We can use either a .NET Command Prompt, or DOS Command Prompt.
By using .NET Command Prompt,
goto the directory where Service is located,
type installutil <servicename.exe>, to uninstall, type installutil /u <servicename.exe>
By Using DOS Command Prompt,
If .NET is not installed in your application, then to install this windows service, must needs .net framework.
goto the directory where installutil.exe is exists.
(by default, in server machines, it is in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727)
in DOS Command prompt, goto that path, and then type installutil C:/services/servicename.exe
(give complete path and name of service to install, same to unsintsall.)
By using .NET Command Prompt,
goto the directory where Service is located,
type installutil <servicename.exe>, to uninstall, type installutil /u <servicename.exe>
By Using DOS Command Prompt,
If .NET is not installed in your application, then to install this windows service, must needs .net framework.
goto the directory where installutil.exe is exists.
(by default, in server machines, it is in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727)
in DOS Command prompt, goto that path, and then type installutil C:/services/servicename.exe
(give complete path and name of service to install, same to unsintsall.)
Thursday, May 19, 2011
HOW TO DELETE WINDOWS SERVICE MANUALLY
Goto Command Prompt and Type 'RegEdit'
and Navigate As Follows :
My Computer >> HKEY_LOCAL_MACHINE >> SYSTEM >> CurrentControlSet >> Services
and Navigate As Follows :
My Computer >> HKEY_LOCAL_MACHINE >> SYSTEM >> CurrentControlSet >> Services
Wednesday, March 30, 2011
Windows XP Run Command List
- Accessibility Controls – access.cpl
- Accessibility Wizard – accwiz
- Add Hardware – Wizardhdwwiz.cpl
- Add/Remove Programs – appwiz.cpl
- Administrative Tools control – admintools
- Adobe Acrobat (if installed) – acrobat
- Adobe Designer (if installed)- acrodist
- Adobe Distiller (if installed)- acrodist
- Adobe ImageReady (if installed)- imageready
- Adobe Photoshop (if installed)- photoshop
- Automatic Updates – wuaucpl.cpl
- Bluetooth Transfer Wizard – fsquirt
- Calculator – calc
- Certificate Manager – certmgr.msc
- Character Map – charmap
- Check Disk Utility – chkdsk
- Clipboard Viewer – clipbrd
- Command Prompt – cmd
- Component Services – dcomcnfg
- Computer Management – compmgmt.msc
- Control Panel – control
- Date and Time Properties – timedate.cpl
- DDE Shares – ddeshare
- Device Manager – devmgmt.msc
- Direct X Control Panel (If Installed)- directx.cpl
- Direct X Troubleshooter- dxdiag
- Disk Cleanup Utility- cleanmgr
- Disk Defragment- dfrg.msc
- Disk Management- diskmgmt.msc
- Disk Partition Manager- diskpart
- Display Properties (w/Appearance Tab Preselected)- control color
- Display Properties- control desktop
- Display Properties- desk.cpl
- Dr. Watson System Troubleshooting Utility- drwtsn32
- Driver Verifier Utility- verifier
- Event Viewer- eventvwr.msc
- File Signature Verification Tool- sigverif
- Files and Settings Transfer Tool- migwiz
- Findfast- findfast.cpl
- Firefox (if installed)- firefox
- Folders Properties- control folders
- Fonts- control fonts
- Fonts Folder- fonts
- Free Cell Card Game- freecell
- Game Controllers- joy.cpl
- Group Policy Editor (XP Prof)- gpedit.msc
- Hearts Card Game- mshearts
- Help and Support- helpctr
- HyperTerminal- hypertrm
- Iexpress Wizard- iexpress
- Indexing Service- ciadv.msc
- Internet Connection Wizard- icwconn1
- Internet Explorer- iexplore
- Internet Properties- inetcpl.cpl
- Internet Setup Wizard- inetwiz
- IP Configuration (Delete DNS Cache Contents)- ipconfig /flushdns
- IP Configuration (Display Connection Configuration) – ipconfi/all
- IP Configuration (Display DHCP Class ID)- ipconfig/showclassid
- IP Configuration (Display DNS Cache Contents)- ipconfig /displaydns
- IP Configuration (Modifies DHCP Class ID)- ipconfig /setclassid
- IP Configuration (Release All Connections)- ipconfig /release
- IP Configuration (Renew All Connections)- ipconfig /renew
- IP Configuration(RefreshesDHCP&Re-RegistersDNS)-ipconfig/registerdns
- Java Control Panel (If Installed)- javaws
- Java Control Panel (If Installed)- jpicpl32.cpl
- Keyboard Properties – control keyboard
- Local Security Settings – secpol.msc
- Local Users and Groups – lusrmgr.msc
- Logs You Out Of Windows – logoff…..
- Malicious Software Removal Tool – mrt
- Microsoft Access (if installed) – access.cpl
- Microsoft Chat – winchat
- Microsoft Excel (if installed) – excel
- Microsoft Frontpage (if installed)- frontpg
- Microsoft Movie Maker – moviemk
- Microsoft Paint – mspaint
- Microsoft Powerpoint (if installed)- powerpnt
- Microsoft Syncronization Tool – mobsync
- Microsoft Word (if installed)- winword
- Minesweeper Game – winmine
- Mouse Properties – control mouse
- Mouse Properties – main.cpl
- Nero (if installed)- nero
- Netmeeting – conf
- Network Connections – control netconnections
- Network Connections – ncpa.cpl
- Network Setup Wizard – netsetup.cpl
- Notepad – notepad
- Nview Desktop Manager (If Installed)- nvtuicpl.cpl
- Object Packager – packager
- ODBC Data Source Administrator- odbccp32.cpl
- On Screen Keyboard – osk
- Opens AC3 Filter (If Installed) – ac3filter.cpl
- Outlook Express – msimn
- Paint – pbrush
- Password Properties – password.cpl
- Performance Monitor – perfmon.msc
- Phone and Modem Options – telephon.cpl
- Phone Dialer – dialer
- Pinball Game – pinball
- Power Configuration – powercfg.cpl
- Printers and Faxes – control printers
- Printers Folder – printers
- Private Character Editor – eudcedit
- Quicktime (If Installed)- QuickTime.cpl
- Real Player (if installed)- realplay
- Regional Settings – intl.cpl
- Registry Editor – regedit
- Registry Editor – regedit32
- Remote Access Phonebook – rasphone
- Remote Desktop – mstsc
- Removable Storage – ntmsmgr.msc
- Removable Storage Operator Requests – ntmsoprq.msc
- Resultant Set of Policy (XP Prof) – rsop.msc
- Scanners and Cameras – sticpl.cpl
- Scheduled Tasks – control schedtasks
- Security Center – wscui.cpl
- Services – services.msc
- Shared Folders – fsmgmt.msc
- Shuts Down Windows – shutdown
- Sounds and Audio – mmsys.cpl
- Spider Solitare Card Game – spider
- SQL Client Configuration – cliconfg
- System Configuration Editor – sysedit
- System Configuration Utility – msconfig
- System File Checker Utility (Purge File Cache)- sfc /purgecache
- System File Checker Utility (Return to Default Setting)- sfc /revert
- System File Checker Utility (Scan Immediately)- sfc /scannow
- System File Checker Utility (Scan On Every Boot) – sfc /scanboot
- System File Checker Utility (Scan Once At Next Boot)- sfc /scanonce
- System File Checker Utility (Set Cache Size to size x)-sfc/cachesize=x
- System Information – msinfo32.
- System Properties – sysdm.cpl
- Task Manager – taskmgr
- Task Manager – taskmgr
- TCP Tester – tcptest
- Telnet Client – telnet
- Tweak UI (if installed) – tweakui
- User Account Management- nusrmgr.cpl
- Utility Manager – utilman
- Windows Address Book – wab
- Windows Address Book Import Utility – wabmig
- Windows Backup Utility (if installed)- ntbackup
- Windows Explorer – explorer
- Windows Firewall- firewall.cpl
- Windows Magnifier- magnify
- Windows Management Infrastructure – wmimgmt.msc
- Windows Media Player – wmplayer
- Windows Messenger – msmsgs
- Windows Picture Import Wizard (need camera connected)- wiaacmgr
- Windows System Security Tool – syskey
- Windows Update Launches – wupdmgr
- Windows Version (to show which version of windows)- winver
- Windows XP Tour Wizard – tourstart
- Wordpad – write
Tuesday, March 29, 2011
GRID VIEW BINDING WITH TEMPLATE FIELDS DYNAMICALLY - ASP.NET with C#
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
namespace SomeName.Classes
{
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string columnNameBinding;
private string controlType;
private int ctrllength;
public GridViewTemplate(DataControlRowType type, string colname, string colNameBinding, string ctlType,int length)
{
templateType = type;
columnName = colname;
columnNameBinding = colNameBinding;
controlType = ctlType;
ctrllength = length;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
if (controlType == "Label")
{
Label lb = new Label();
lb.ID = "lbl_" + columnNameBinding;
lb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
container.Controls.Add(lb);
}
else if (controlType == "TextBox")
{
TextBox tb = new TextBox();
tb.ID = "tb" + columnNameBinding;
tb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
tb.Width = ctrllength;
container.Controls.Add(tb);
}
else if (controlType == "CheckBox")
{
CheckBox cb = new CheckBox();
cb.ID = "cb1" + columnNameBinding;
cb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
container.Controls.Add(cb);
}
else if (controlType == "HyperLink")
{
HyperLink hl = new HyperLink();
hl.ID = "hl1";
hl.DataBinding += new EventHandler(this.ctl_OnDataBinding);
container.Controls.Add(hl);
}
else if (controlType == "HiddenField")
{
HiddenField hf = new HiddenField();
hf.ID = "hf" + columnNameBinding;
hf.DataBinding += new EventHandler(this.ctl_OnDataBinding);
container.Controls.Add(hf);
}
break;
default:
break;
}
}
public void ctl_OnDataBinding(object sender, EventArgs e)
{
if (sender.GetType().Name == "Label")
{
Label lb = (Label)sender;
GridViewRow container = (GridViewRow)lb.NamingContainer;
lb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
}
else if (sender.GetType().Name == "TextBox")
{
TextBox tb = (TextBox)sender;
GridViewRow container = (GridViewRow)tb.NamingContainer;
tb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
}
else if (sender.GetType().Name == "CheckBox")
{
CheckBox cb = (CheckBox)sender;
GridViewRow container = (GridViewRow)cb.NamingContainer;
cb.Checked = Convert.ToBoolean(((DataRowView)container.DataItem)[columnNameBinding].ToString());
}
else if (sender.GetType().Name == "HyperLink")
{
HyperLink hl = (HyperLink)sender;
GridViewRow container = (GridViewRow)hl.NamingContainer;
hl.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
hl.NavigateUrl = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
}
else if (sender.GetType().Name == "HiddenField")
{
HiddenField hf = (HiddenField)sender;
GridViewRow container = (GridViewRow)hf.NamingContainer;
hf.Value = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Place the above class seperately and
//////////////Use the Following code in aspx.cs,
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
string strColName="Some DaField Column Name";
string strColLabel = "Header text";
TemplateField tField = new TemplateField();
tField.HeaderText = strColLabel;
tField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, strColLabel, strColName, "", 0);
if (Some Condition)
tField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "", strColName, "Label", 100);
else
tField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "",strColName, "TextBox", 100);
grdMapValues.Columns.Add(tField);
}
if (dtMapData.Rows.Count > 0)
{
grdMapValues.DataSource = dtMapData;
grdMapValues.DataBind();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////In Code Behind, the Gridview is like this
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<asp:GridView ID="grdname" runat="server"
CssClass="GridStyle" ShowHeader="true" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField><ItemTemplate></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////In Code Behind, the Gridview is like this
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<asp:GridView ID="grdname" runat="server"
CssClass="GridStyle" ShowHeader="true" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField><ItemTemplate></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
Subscribe to:
Posts (Atom)