代码改变世界

GridView控件删除记录时出现索引超出范围问题的解决

2010-01-05 13:38  端木非  阅读(786)  评论(0编辑  收藏  举报

废话少说,直奔主题:

问题:

在下面一段代码测试时,老是在运行点击删除按钮时出现:索引超出范围,参数index

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
        string strCon = "server=(local);database=my51aspx;uid=sa;pwd=sa";
        SqlConnection conn = new SqlConnection(strCon);
        conn.Open();
        string strCmd = "delete from province where id="+id;
        SqlCommand cmd = new SqlCommand(strCmd,conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        bing();
    }

bing()函数源码为:

protected void bing()
    {
        string strCon = "server=(local);database=my51aspx;uid=sa;pwd=sa";
        SqlConnection conn = new SqlConnection(strCon);
        conn.Open();
        string strCmd="select * from province";
       
        SqlDataAdapter da = new SqlDataAdapter(strCmd,conn);
        DataSet ds= new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
                GridView1.DataBind();
        conn.Close();
    }

 

 

问题原因:

 

 

没有为GridView设置主键。

 

 

 

解决办法:

在bing()函数中加上一句:

GridView1.DataKeyNames = new string[] { "id"};//设置主键(这一句最好放在GridView1.DataBind();上面)

保存代码,再次运行,一切就OK了。