索引超出范围。必须为非负值并小于集合大小。

来源:百度知道 编辑:UC知道 时间:2024/07/02 04:05:33
在asp:GridView中,点删除按钮时出现的问题,VS2005环境
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//得到编号

int sid = (int)GridView1.DataKeys[e.RowIndex].Value;
Response.Write(sid);
//从数据库中删除
string sql = "DELETE FROM admin where id=" + sid;
access.DoSql(sql);
Bind();
}

出现的错误:
索引超出范围。必须为非负值并小于集合大小。
参数名: index
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.ArgumentOutOfRangeException: 索引超出范围。必须为非负值并小于集合大小。
参数名: index

源错误:

行 58: //得到编号
行 59:
行 60: int sid = (int)GridView1.DataKeys[e.RowIndex].Value;
行 61: Response.Write(sid);
行 62: //从数据库中删除

请高手指点怎么回事.谢谢.

int sid = (int)GridView1.DataKeys[e.RowIndex].Value;
改成:
int sid = (int)GridView1.DataKeys[e.Item.ItemIndex];

我以前写程序,是这样写的~!你试一下可不可以用

=========================================
我以前写了一个"孤心夜雪个人主页",开放源码,你从网上下载一份看看,里面也有用到DataGrid及其它的东东,也许对你有用!