Getting controls of Gridview in C# code behind

In this tutorial we will learn how to get different controls of gridview in C# code behind. We normally get data from database and display it in gridview using different controls in gridview like label, textbox etc. In some cases we do need to get these controls of gridview in our C# code. Let’s have a look on how to get the gridviews' controls in C#.


Working_Gridview_Controls.aspx

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%" HorizontalAlign="Left" GridLines="None" EmptyDataRowStyle-ForeColor="Maroon" EmptyDataText="No Record(s) Found" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table border="0" style="width:100%; border:1px solid #e4e4e4" cellpadding="2" cellspacing="4">
<tr bgcolor="#e4e4e4" style="font-family:Verdana; font-size:10px;">
<td width="3%" align="center">
<asp:Label ID="lbl_Name" runat="server" Font-Bold="true"></asp:Label>
<asp:Label ID="lbl_City" runat="server" Font-Bold="true"></asp:Label>

<asp:Label ID="lbl_State" runat="server" Font-Bold="true"></asp:Label>

</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Working_Gridview_Controls.aspx.cs

public partial class special_instruction : System.Web.UI.Page
{
string myVar;


protected void Page_Load(object sender, EventArgs e)
{
//Your code will come here
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if(e.Row.RowType== DataControlRowType.DataRow)
{

myVar = ((Label)e.Row.FindControl("lbl_Name")).Text;

}

}

}

In Working_Gridview_Controls.aspx.cs I declared a global variable myVar and in rowdatabound event of gridview using this code ((Label)e.Row.FindControl("lbl_Srno")).Text; i get the Label Control of Gridview, in this example I am getting the Label having the id lbl_Name which lies inside the gridview.

So this is the way to get the gridviews' controls in C# and have fun :)

0 comments: