Home > DeveloperSection > Forums > FindControl in gridview returns null
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    August-18-2014 3:20 AM

 C# C# 
Ratings:


 1 Reply(s)
 1066  View(s)
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"



Pravesh Singh

Total Post:411

Points:2881
Posted on    August-18-2014 3:40 AM

Hi Jeet, 

GridView gv1 = (GridView)sender;

GridViewRow rvRow = gv1.SelectedRow;

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


Don't want to miss updates? Please click the below button!

Follow MindStick