如何获取网格视图的模板字段标签的值,获取错误对象引用未设置为对象实例

本文关键字:获取 取错误 对象引用 设置 实例 对象 标签 何获取 网格 视图 字段 | 更新日期: 2023-09-27 18:27:53

在获取值时,我正在获取对象引用,该引用未设置为对象的实例。如何在代码隐藏中获得标签值。如何在自定义事件中获取值

<asp:GridView runat="server" ID="gridviewQuoteDetails" EmptyDataText="No records Found..." AutoGenerateEditButton="false" OnRowEditing="gridviewQuoteDetails_RowEditing" OnRowUpdating="gridviewQuoteDetails_RowUpdating" DataKeyNames="id" AutoGenerateColumns="false">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <a href='Quote.aspx?val=<%#Eval("id")%>'>
                                <asp:Label ID="lblid" runat="server" Text='<%#Eval ("id")%>'></asp:Label>
                            </a>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" CommandName="Edit" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton ID="LinkButton2" Text="Update" runat="server" OnClick="OnUpdate" />
        </EditItemTemplate>
    </asp:TemplateField>
                </Columns>
    </asp:GridView>

        code behind

     protected void OnUpdate(object sender, EventArgs e)
        {
                string qouteid = ((Label)gridviewQuoteDetails.FindControl("lblid")).Text;
                GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
                string id = (row.Cells[0].Controls[0] as TextBox).Text;
                string Description = (row.Cells[1].Controls[0] as TextBox).Text;  
        }

如何获取网格视图的模板字段标签的值,获取错误对象引用未设置为对象实例

Gridview是一个右侧行的集合,但您正试图直接在网格视图中搜索控件,因此((LinkButton)gridviewQuoteDetails.FindControl("lbllnknm"))将为null,并且当您试图访问LinkButton的Text属性时,您会收到NRE错误。

您需要循环浏览网格视图控件的行,以访问每行中的每个链接按钮,如下所示:-

foreach (GridViewRow row in gridviewQuoteDetails.Rows)
{
    LinkButton lbllnknm= row.FindControl("lbllnknm") as LinkButton;
}

但理想情况下,你不需要这个。我猜您正在尝试获取OnRowEditing事件处理程序中的值。如果是这样的话,那么你可以像这样获取链接按钮的值:-

protected void gridviewQuoteDetails_RowEditing(object sender, GridViewUpdateEventArgs e)
{
    string qouteid = ((Label)gridviewQuoteDetails.Rows[e.NewEditIndex]
                                                 .FindControl("lbllnknm")).Text;
}

更新2:

根据您的评论,您正试图在单击LinkButton本身时访问LinkButton文本,这意味着事件是由LinkButton本身引发的。您可以简单地使用sender对象,如下所示:-

protected void OnUpdate(object sender, EventArgs e)
{
    LinkButton LinkButton2 = sender as LinkButton;
    GridViewRow row = LinkButton2.NamingContainer as GridViewRow; //Get the gridview row
    Label lblid = row.FindControl("lblid") as Label;
    string qouteid = lblid.Text;
}