我在我的DATAGRID中的删除按钮列中编码如下
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName=="Delete")
{
dbutil dtl=new dbutil();
                this.DataGrid1.DataKeyField="itemid";
string itemid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
this.Label1.Text=itemid;
SqlCommand cmd2=new SqlCommand();
cmd2.Connection=new SqlConnection(dtl.constr());
string sqlstr2="delete from lineitem where orderid="+Page.Session["orderid"]+" AND itemid="+itemid+"";
cmd2.CommandText=sqlstr2;
cmd2.CommandType=CommandType.Text;
cmd2.Connection.Open();
cmd2.ExecuteNonQuery();
cmd2.Connection.Close();
SqlCommand cmd4=new SqlCommand();
cmd4.Connection=new SqlConnection(dtl.constr());
string sqlstr4="select price,quantity,item.itemid from lineitem ,item where orderid="+Page.Session["orderid"]+"AND item.itemid=lineitem.itemid";
cmd4.CommandText=sqlstr4;
cmd4.CommandType=CommandType.Text;
SqlDataAdapter da4=new SqlDataAdapter(cmd4);
DataSet ds4=new DataSet();
da4.Fill(ds4);
this.DataGrid1.DataSource=ds4.Tables[0];
                
this.DataGrid1.DataBind();
}
运行时系统提示错误是:索引超出范围。必须为非负值并小于集合大小。参数名: index 
请高手们解决下,解决马上给分

解决方案 »

  1.   

    private void Button1_Click(object sender, System.EventArgs e)
    {
    dbutil dtl=new dbutil();
    for(int i=0;i<this.DataGrid1.Items.Count;i++)
    {System.Web.UI.WebControls.TextBox tt=(System.Web.UI.WebControls.TextBox)this.DataGrid1.Items[i].FindControl("textbox1");
                this.DataGrid1.DataKeyField="itemid";
    string str=this.DataGrid1.DataKeys[i].ToString();
    this.Label1.Text=str;
    SqlCommand cmd2=new SqlCommand();
    cmd2.Connection=new SqlConnection(dtl.constr());
    string sqlstr2="update lineitem set quantity="+Convert.ToInt32(tt.Text)+" where itemid="+str+" AND orderid="+Page.Session["orderid"]+"";
    cmd2.CommandText=sqlstr2;
    cmd2.CommandType=CommandType.Text;
    cmd2.Connection.Open();
    cmd2.ExecuteNonQuery();
    cmd2.Connection.Close();
    }
    这是我在一个按钮里编码也是一样的啊,顺便帮忙解决下,也提示索引超出范围啊
    我的主键不是itemid不知道是不是这个影响啊
      

  2.   

    出错的句子在string itemid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
    就是说里面的索引出了问题,但是我以前用过都不会啊
      

  3.   

    你是的DataGrid中填充的最后一页的记录都被删除时(一般是最后一页只有一条记录)就会出这个错误。在执行语句前加上这句试试:this.DataGrid1.CurrentPageIndex=0;让DataGrid的索引指向第一页
      

  4.   

    可是我的DATAGRID里只有一页啊
      

  5.   

    我遇到过这个问题
    DataGrid1的属性中有DataKeyField,将你的主键填写在这里,问题就解决了