gridview中的FindControl返回null

时间:2014-04-20 16:34:11

标签: c# asp.net gridview

我目前处于两难境地,我的gridview没有返回标签,这是在详情视图中......

我的C#代码是:

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>

当我断点时

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

标签显示为null(numberLbl)...

异常返回的消息是: &#34;对象引用未设置为对象的实例&#34;

编辑: 如果我使用Eval(&#34; NUMBER&#34;)在外部gridview(在页面上)生成lblNumber,这似乎得到了解决,尽管我不明白为什么它在当前不起作用我试图使用GridView,因为GridView1在DetailsView中。

1 个答案:

答案 0 :(得分:0)

使用FindControl时不应使用Cell Collection。只需使用此

GridView gv1 = (GridView)sender;
GridViewRow rvRow = gv1.SelectedRow;
Label numberLbl = (Label)rvRow.FindControl("lblNumber");