第一个问题:
我有一个gridview'gvSnacks',上面有小吃和价格清单。 gridview的第一列是一个带有按钮'btnAdd'的模板字段。
当单击其中一个添加按钮时,我希望它将该行值分配给一个整数,以便我可以从该行检索其他数据。
这就是我所拥有的,但我已经走到了尽头。
protected void btnAdd_Click(object sender, EventArgs e)
{
int intRow = gvSnacks.SelectedRow.RowIndex;
string strDescription = gvSnacks.Rows[intRow].Cells[2].Text;
string strPrice = gvSnacks.Rows[intRow].Cells[3].Text;
}
感谢任何帮助!
答案 0 :(得分:4)
您可能需要使用RowCommand事件:
public event GridViewCommandEventHandler RowCommand
This is the MSDN link for this event
该按钮必须具有CommandName属性,您可以将该行的值放在命令参数中:
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}