GridViewRow Cells在按钮中返回空字符串单击Gridview内的事件启动

时间:2013-09-16 06:43:37

标签: c# asp.net gridview

我对这个问题感到困惑。

我在gridview的模板字段旁边放了一个按钮,并且想要在单击相应的按钮时从特定的GridView Row返回数据。

<asp:TemplateField>
     <ItemTemplate>
          <asp:Button ID="Button2" CssClass ="btnSkin" runat="server" Text="Answer" Width="117px" onclick="Button2_Click" />
     </ItemTemplate>
</asp:TemplateField>

在按钮单击事件fireup中,我想通过创建GridViewRow元素来读取该数据。

protected void Button2_Click(object sender, EventArgs e)
{
     GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
     Label8.Text = gvr.Cells[1].Text;
     Label10.Text = gvr.Cells[2].Text;
     Label12.Text = gvr.Cells[3].Text;
}

现在的问题是,GridViewRow Cells正在返回空字符串。

我该怎么办?????

4 个答案:

答案 0 :(得分:3)

使用<asp:TemplateFields>时,您实际上需要找到控件内的文字,例如您在<asp:Label>中使用的<ItemTemplate>

单元格没有文本,它是具有文本的单元格内的控件。

所以,如果假设您在<ItemTemplate>之一内有一个标签:

<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CustomerID") %>'>
</asp:Label>
</ItemTemplate>

然后使用按钮中的以下代码访问此Label控件的Text单击事件:[假设,第二列包含上面定义的<ItemTemplate>]

protected void Button2_Click(object sender, EventArgs e)
    {
        GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
        String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;
    }

答案 1 :(得分:3)

我找到了空字符串错误背后的原因。

Gridview.Cells[i].Text仅在<asp:BoundField>

时才会返回字符串值

如果是<asp:TemplateField>并且<ItemTemplate>中有一些ASP控件,则必须遵循FindControl("<control_id>")方法。

这里,基本上我们通过其ID在该特定GridviewRow单元格中查找控件对象,并将其转换为相应的控件类型。现在,我们可以使用它,因为我们从代码隐藏调用任何其他asp控件。

String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;

答案 2 :(得分:1)

尝试使用GridView.RowCommand事件并参考以下链接获取相同的

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

希望这会对你有所帮助。

答案 3 :(得分:0)

请检查您是否在Page Load上正确绑定了网格。

  if(!IsPostBack)
{
  BindgridView();
}

希望这会有所帮助。试一试..