索引超出了数组界限。
VS2003 ASP.NET想实现一下,点击删除按钮在DataGrid中删除一条数据
代码如下:
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string pid=this.DataGrid1.DataKeyField[e.Item.ItemIndex].ToString();//--------这里有错误--------
SqlConnection con=db.creatcon();
SqlCommand cmd=new SqlCommand( "delete from student where pid= ' "+pid+ " ' ",con);
con.Open();
cmd.ExecuteNonQuery();
this.databing();//绑定DataGrid的方法
错误:
索引超出了数组界限。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.IndexOutOfRangeException: 索引超出了数组界限。
源错误:
行 114: private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
行 115: {
行 116: string pid=this.DataGrid1.DataKeyField[e.Item.ItemIndex].ToString();//此行有错误
行 117:
行 118: SqlConnection con=db.creatcon();
困扰我好几天了,有碰到此问题的,或者站点怎么解决的前辈们.多多指教,谢谢
------解决方案--------------------DataGrid 设置DataKeyField属性了吗?
string pid=this.DataGrid1.DataKeyField[e.Item.ItemIndex].ToString();
==================================================================
string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
------解决方案--------------------先
if (e.Item.ItemIndex == -1)
return;
然后再:
string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].value; // 只有一个主键的情况
或者:
string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex][ "列 "].value; // 多个主键的情况