获取值时,我得到的对象引用未设置为对象的实例。如何在代码后面获得标签标签值。如何获取自定义事件中的值
<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;
}
答案 0 :(得分:0)
Gridview
是行的集合,但是您尝试直接在gridview中搜索控件,因此((LinkButton)gridviewQuoteDetails.FindControl("lbllnknm"))
将为null并且当您尝试访问Text
属性时LinkButton你得到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:
根据您的评论,您尝试在点击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;
}