单击模板字段命令按钮时获取gridview单元格值

时间:2016-08-21 17:52:26

标签: c# asp.net gridview

我在模板字段中有一个带有命令按钮的gridview。 如果不首先选择行,我如何在命令按钮上点击事件中的第一个单元格值?

为了测试,我尝试设置标签文本值,但我认为因为行不是先选择,所以它不起作用

Label3.Text = "test " + GridView1.SelectedRow.Cells[1].Text;

1 个答案:

答案 0 :(得分:0)

您可以在按钮中将行号作为CommandArgument发送。

<asp:Button ID="Button1" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="Button1_Command" runat="server" Text="Button" />

从后面的代码中的行和列中获取正确的值。

protected void Button1_Command(object sender, CommandEventArgs e)
{
    Label3.Text = "test " + GridView1.Rows[Convert.ToInt32(e.CommandArgument)].Cells[1].Text;    
}

如后所述,您需要将GridView的绑定包装成!IsPostBack,否则您将收到“无效的回发或回调参数”错误。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = myDataSource;
        GridView1.DataBind();
    }
}
  

请注意,只搜索GridView单元格(Rows [0] .Cells [1] .Text)   适用于BoundField列,而不是TemplateField和AutoGenerated   列。