写在某Button里面的。
            string sql;
            StringBuilder buff = new StringBuilder();
            oleDbConnection2.Open();
            sql = buff.Append("delete  from 表1 where name='")
            .Append(dataGridView1.SelectedRows[0].Cells[1]).Append("'").ToString();
            oleDbInsertCommand1.CommandText = sql;
            MessageBox.Show(oleDbInsertCommand1.ExecuteNonQuery().ToString());
            oleDbConnection2.Close();
就是想在数据库里删除dgv中被选中的行,运行时出现:
索引超出范围。必须为非负值并小于集合大小。
参数名: index
该怎么办?
另外,应该有比这个更好的方法吧?求教~!

解决方案 »

  1.   

    dataGridView1.SelectedRows[0].Cells[1] 没有选中DataGridView1的行把
      

  2.   

                 string sql;
                StringBuilder buff = new StringBuilder();
                oleDbConnection2.Open();
                sql = buff.Append("delete  from 表1 where 1=1 ")
                if(dataGridView1.SelectedRows.Count>0)
              {  
                buff.Append(" AND name='")
                buff.Append(dataGridView1.SelectedRows[0].Cells[1].Value.ToString());
                buff.Append("'").ToString();
                }
                oleDbInsertCommand1.CommandText = sql;
                MessageBox.Show(oleDbInsertCommand1.ExecuteNonQuery().ToString());
                oleDbConnection2.Close();
      

  3.   

    没有选中你想要的值啊!
    你要选择的应该是这一行里面的Cell[1].Controls[0] 的值。这个Controls[0]可能是TextBox,或者是Lable,需要强制转换一下,然后取得他们的Text属性。
    最好是用DataKeys获取你选中行的主键值。这样比较方便。
    个人意见,呵呵……
    我也是新人
      

  4.   

    知道原因了,我选中的是里面的cell而不是一行。
    要是选中cell的话,可不可以删除cell所在的行?
      

  5.   

    只要取到name的值就好了,选择是name的cell 或者选择name所在的行都可以哇
    debug下 改下下标数字看看到底是哪个
      

  6.   

    我同意七楼的看法,没有获得所用控件的text值也就是 数据库 name字段 相应的值
    建议使用 DataKeys