[英]Get GridView row index from a template field button
第一個問題:
我有一個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;
}
感謝任何幫助!
您可能需要使用RowCommand事件:
public event GridViewCommandEventHandler RowCommand
該按鈕必須具有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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.