getting gridview cell values when clicking template field command button

邮差的信 提交于 2019-12-25 06:46:43

问题


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;

回答1:


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.



来源:https://stackoverflow.com/questions/39067181/getting-gridview-cell-values-when-clicking-template-field-command-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!