FINDCONTROL IN GRIDVIEW RETURNS NULL

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
C# 
C#
 1471  View(s)
Ratings:
Rate this:

I am currently in a dilemma with my gridview not returning a label, which is within a detailsview...

My C# code is:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

    // get pet number for when removing a pet from reservation

    int numberSelected = -1;

    String numbertxt = "-1";

    GridView gv1 = (GridView)sender;

    GridViewRow rvRow = gv1.Rows[gv1.SelectedRow.RowIndex];

    Label numberLbl = (Label)rvRow.Cells[0].FindControl("lblNumber");

    // find selected index, and get number in column 0

    // label within GridView1 within dvReservation DetailsView

    numbertxt = numberLbl.Text;

    ...

Gridview:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

    DataSourceID="dsObjGet"

    OnSelectedIndexChanged="GridView1_SelectedIndexChanged">

    <Columns>

        <asp:TemplateField InsertVisible="False" ShowHeader="False">

            <AlternatingItemTemplate>

                <asp:Label ID="lblNumber" runat="server"

                    Text='<%# Eval("NUMBER") %>' Visible="False"></asp:Label>

            </AlternatingItemTemplate>

            <ItemTemplate>

                <asp:Label ID="lblNumber" runat="server"

                    Text='<%# Eval("NUMBER") %>' Visible="False"></asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField ShowHeader="False">

            <AlternatingItemTemplate>

                <asp:Label ID="lblName" runat="server" Text='<%# Eval("NAME") %>'>

                </asp:Label>

            </AlternatingItemTemplate>

            <ItemTemplate>

                <asp:Label ID="lblName" runat="server" Text='<%# Eval("NAME") %>'>

                </asp:Label>

            </ItemTemplate>

        </asp:TemplateField>

        <asp:CommandField SelectText="Remove" ShowSelectButton="True"

            CausesValidation="False">

            <ControlStyle CssClass="link" />

        </asp:CommandField>

    </Columns>

</asp:GridView>

When I breakpoint

Label numberLbl = (Label)rvRow.Cells[0].FindControl("lblNumber");

the label comes out as null (numberLbl)...

The message returned from the exception is: "Object reference not set to an instance of an object"

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: FindControl in gridview returns null

    Hi Jeet, 


    GridView gv1 = (GridView)sender;

    GridViewRow rvRow = gv1.SelectedRow;

    Label numberLbl = (Label)rvRow.FindControl("lblNumber");

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!