【问题标题】:Get GridView row index from a template field button从模板字段按钮获取 GridView 行索引
【发布时间】:2012-12-06 21:41:24
【问题描述】:

第一个问题:

我有一个网格视图“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;
}

感谢任何帮助!

【问题讨论】:

  • 问题是如何在单击“添加”按钮之一时将 gridview 行分配给整数?
  • 你当前的代码有什么问题?
  • 如果您是 ASP 新手,我建议您花时间学习使用 ListView 而不是 GridView。在我看来,它们更强大。

标签: c# asp.net


【解决方案1】:

您可能需要使用 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);
      }
    }
  }    

【讨论】:

  • 欣赏这个!我真的很喜欢在一个 rowcommand 下处理不同参数的能力!
猜你喜欢
  • 2013-12-03
  • 2013-04-21
  • 1970-01-01
  • 2011-12-13
  • 2015-12-25
  • 1970-01-01
  • 2015-03-26
  • 2012-02-22
  • 1970-01-01
相关资源
最近更新 更多