问题
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