且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-20 16:26:19

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

 < asp:Button ID =Button1CommandArgument ='<%#Container.DataItemIndex%>' OnCommand =Button1_Commandrunat =serverText =Button/> 

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

  protected void Button1_Command(object sender,CommandEventArgs e)
{
Label3.Text =test+ GridView1.Rows [Convert。 ToInt32(e.CommandArgument)]细胞[1]。文本。
}

正如后面发现的那样,您需要将GridView绑定到一个! IsPostBack,否则你会得到一个无效的回发或回调参数错误。

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






lock $ $ $ b $ p注意到搜索GridView像这样的单元格(行[0] .Cells [1] .Text)只有
适用于BoundField列,而不适用于TemplateField和AutoGenerated
列。


I have a gridview with a command button in a template field. Without selecting the row first, how can I grab the first cell value on the command buttons on-click event?

To test, I tried to set a labels text value but I think that as the row is not select first, it won't work

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

You can send the row number as a CommandArgument in the button.

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

And grab the correct value from the row and column in code behind.

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

As discovered later, you need to wrap the binding of the GridView into a !IsPostBack, otherwise you'll get an "Invalid postback or callback argument" error.

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

Note that searching GridView cells like this (Rows[0].Cells[1].Text) only works with BoundField columns, not TemplateField and AutoGenerated Columns.