为什么索引超出范围异常?

why index out of range exception?

我正在使用此代码在 gridview 中获取 last row 的索引,然后将空字符串放入特定单元格但抛出错误:Index out of range

protected void grdViewAdvances_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {
        int RowIndex = grdViewAdvances.Rows.Count-1 ;

        grdViewAdvances.Rows[RowIndex].Cells[5].Text = "";
    }

每行 RowDataBound 事件的行数都会发生变化。如果要更改最后一行列的文本,则让绑定过程完成并在 RowDataBound 之后分配空字符串。

你可能需要在 DataBind() 方法之后做。

grdViewAdvances.DataSource = dt;
grdViewAdvances.DataBind();
grdViewAdvances.Rows[RowIndex].Cells[5].Text = "";

编辑

我刚刚调试了代码,当第一次在 if 语句下执行代码时,你的行计数为零,从中减去一个会给你行 = -1,这肯定是超出界限的索引。