How to call control inside GridView

There are many cases when we need to call the control which is present inside anyother control. I am showing when GridView is having the contol. We will do this by using Findcontrol Method present inside the GridView. You can use this method for any other control inside which you have placed anohter control.

Suppose you have Label inside the GridView.You need to use Templatefield to put the Label inside the GidView.

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_OnRowDataBound">
<asp:Label ID="Label" runat="server" Text="Test"></asp:Label>

Your label can be called inside the function GridView_OnRowDataBound()
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        Label label = new Label();
        label = (Label) e.Row.FindControl("Label");
        label.Text = "Working";   


The object findcontrol is returning have to be converted into the Label class explicitly. Also you need to instantiate the label with new operator otherwise it will give NullReference Complilation Error, as if your findcontrol method returns null value it would not be accepted.

in case you want to call this label in any other function with help of GridView control that can be possible also
  Label lbl = new Label();
        lbl =(Label) GridView1.FindControl("GridView1");

withhelp of  findcontrol method you can find any control at first level. Suppose you have hierarchy condition where Label is inside the Panel and Panel in side GridView .
You can use to findcontrol to find the panel and then label

here is small code how it will look

            Panel pnlTestLocal = new Panel();
             pnlTestLocal = (Panel) gvTest.FindControl("pnlTest");
             Label lblTestLocal = new Label();
             lblTestLocal = (Label)pnlTestLocal.FindControl("lblTest");
             lblTestLocal.Text = "Working";

Also it templatefild will look like this

    <asp:Panel ID="pnlTest" runat="server">
    <asp:Label ID="lblTest" runat="server" Text="Test"></asp:Label>
    <asp:Button ID="btnTest" runat="server" Text="check"  CommandName="check" CommandArgument="chk"/>