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

时间:2015-12-24 09:27:05

标签: c# asp.net gridview

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

<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;  
        }

1 个答案:

答案 0 :(得分:0)

Gridview是行的集合,但是您尝试直接在gridview中搜索控件,因此((LinkButton)gridviewQuoteDetails.FindControl("lbllnknm"))将为null并且当您尝试访问Text属性时LinkBut​​ton你得到NRE错误。

您需要循环遍历gridview控件的行,以访问每行中的每个链接按钮,如下所示: -

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

但理想情况下你不需要这个。我猜你试图在OnRowEditing事件处理程序中获取值。如果是这种情况,那么你可以像这样获取linkbutton的值: -

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

更新2:

根据您的评论,您尝试在点击LinkBut​​ton本身时访问LinkBut​​ton文本,这意味着事件由LinkBut​​ton本身引发。您可以像这样简单地使用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;
}