【问题标题】:How to get datakeys value in a gridview如何在网格视图中获取数据键值
【发布时间】:2012-06-20 11:30:44
【问题描述】:

我尝试删除 Gridview 和 Database 中的一条记录。我添加了一个 boundfield 按钮并在 RowCommand 事件中将 CommandName 设置为 Deleterecord 我想获取此记录的主键以删除它(主键值未显示在网格视图中。以下代码块显示了此事件(我尝试在文本框中显示一些数据):

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "Deleterecord")
            {
                TextBox1.Text = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString(); 
                   //bla bla
            }
        }

我也设置了

DataKeyName="sourceName"

在网格视图中,但它不是我的主键

如果我单击此按钮,则会发生如下异常: 索引超出范围。必须是非负数且小于集合的大小。 参数名称:索引 我该如何解决这个问题

【问题讨论】:

标签: asp.net


【解决方案1】:

使用这个

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Deleterecord")
    {
         LinkButton lb = (LinkButton)e.CommandSource;
         GridViewRow gvr = (GridViewRow)lb.NamingContainer;

         TextBox1.Text = grid.DataKeys[gvr.RowIndex].Value.ToString(); 
         //bla bla
    }
}

此处的LinkButton 应替换为执行此RowCommand 事件的控件类型

欲了解更多信息,请转到Here

【讨论】:

  • 为什么现在有什么问题??
  • 无法将“System.Web.UI.WebControls.GridView”类型的对象转换为“System.Web.UI.WebControls.Button”类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多