我有一个带有模板字段的GridView,而连接字符串位于
web.config 文件。数据由存储过程提取。我想在protected void someMethod(object sender, EventArgs e)
事件的OnClick="someMethod"
中检索Gridview的单个单元格值。但它最终得到:
对象引用未设置为对象的实例。
生成OnClick
事件的代码:
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="someMethod">Get Name</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
我想得到的Gridview Cell的价值是:
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="forNames" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="eForNames" runat="server" Text = '<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
代码背后是:
protected void someMethod(object sender, EventArgs e)
{
Label ename = diplayAdapter.SelectedRow.FindControl("eForNames") as Label;
Label5.Text = ename.Text;
}
答案 0 :(得分:1)
.ASPX代码:
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandArgument="<%# Container.DisplayIndex %>" runat="server" CommandName="FindName">Get Name</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="forNames" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="eForNames" runat="server" Text = '<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
.CS代码
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//getting rowindex which we have selected by using CommandArgument
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "FindName")
{
Label5.Text= GridView1.Rows[rowindex].Cells[1].FindControl("eForNames");
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}