【问题标题】:Index was out of range. Must be non-negative and less than the size of the collection.指数超出范围。必须是非负数且小于集合的大小。
【发布时间】:2017-04-06 12:52:26
【问题描述】:

我收到错误消息(索引超出范围。必须为非负数且小于集合的大小。 GridView_RowUpdating 事件中的参数名称:index)。我尝试了这里发布的一些想法,但仍然出现此错误。

代码背后

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label stu_name= ((Label)GridView1.Rows[e.RowIndex].FindControl("student_Name"));
}

【问题讨论】:

  • 尝试调试。可能是-1,当没有选择行时。
  • 正确显示 rowindex(e.RowIndex)
  • 在 'GridView1.Rows.Count' 和 'e.RowIndex' 的调试过程中添加 Watch 并共享两个表达式的结果以调查问题。
  • ohhh.. 它显示 GridView1.Rows.Count 为 0 和 e.RowIndex 为 1(选定的行索引)
  • 您是否为 GridView1 控件启用了 ViewState?如果不是 ASP.NET 将无法正常工作以更新 GridView。

标签: c# asp.net


【解决方案1】:

检查是否为 GridView1 启用了 ViewState。

如果 ViewState 被禁用,ASP.NET 将无法正确更新,因为 ASP.NET 处理更新或任何其他需要保留以前数据的事件。

如果 ViewState==false,GridView1.Rows[e.RowIndex] 将失败,因为 GridView1.Rows.Count 将为 0。

此外,如果您在 Page_Load 中执行 DataBind,请确保仅在 !IsPostBack 时才进行 DataBind。

if(!IsPostBack)
 // DataBind Grid ..

【讨论】:

  • 刚才我注意到,Rowediting 事件触发两次,第一次显示网格。但第二次显示 EmptyDataTemplate 文本
  • 好的。确保不要在每个 PostBack 上绑定数据。在 DataBind 之前检查 !IsPostBack。
【解决方案2】:

虽然编码人员的偏见是让代码产生所需的结果,但如果发生异常,则意味着它可能再次发生。

很高兴弄清楚所有数据绑定和视图状态的黑魔法,但从一开始就在假设上稍微保守一点可能也是一个好主意:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    var grid = sender as Grid;
    if (grid == null) return;

    var rowIndex = e.RowIndex;
    var rows = grid.Rows;
    if (rowIndex < 0 || rowIndex > rows.Count - 1) return;
    Label stu_name= ((Label) rows[rowIndex].FindControl("student_Name"));
}

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 2012-05-15
    相关资源
    最近更新 更多