日期:2014-05-18  浏览次数:20976 次

datagridview多行删除问题
对选中的datagridview中的多行,不能正确删除,只能删除选定的最后一个,究竟问题出在哪?

代码:
  private void btnDel_Click(object sender, EventArgs e)
  {
  int i = this.dataGridView1.SelectedRows.Count;

  DialogResult dr = MessageBox.Show("删除后不能恢复,确实想删除这"+Convert.ToString(i) +"个用户信息吗?", "友情提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
  if (dr == DialogResult.Yes)
  {
  int t = 0;
  try
  {
  for (int j = 0; dataGridView1.SelectedRows.Count > j; )
  {
  dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
  }

  DBCon oleCon = new DBCon();
  string strSql = "delete from UserInfo where 姓名='" + username + "'";
  t = oleCon.Updata(strSql);

  if (t == 0)
  {
  MessageBox.Show("删除失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }
  else
  {
  string Sql = "select * from UserInfo";
  ds = oleCon.Query(Sql);
  this.dataGridView1.DataSource = ds.Tables[0];
  MessageBox.Show("删除成功!", "提示!", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  }
  else
  {
  return;
  }
  }



  public int Updata(string strSql)
  {
  int t = 0;
  using (OleDbConnection oleCon = new OleDbConnection(strCon))
  {
  oleCon.Open();
  OleDbCommand oleCom = new OleDbCommand();
  oleCom.Connection = oleCon;
  oleCom.CommandText = strSql;
  t = oleCom.ExecuteNonQuery();
  }
  return t;
  }

------解决方案--------------------
把数据库的删除代码放
for (int j = 0; dataGridView1.SelectedRows.Count > j; ) 

dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]); 

这里面来.
------解决方案--------------------
C# code

private void btnDelete_Click(object sender, EventArgs e)
        {
            //判断用户是否选择一行数据,true为没选择,false为选择
            if (this.dgv.Rows[this.dgv.CurrentRow.Index].Cells[0].Value.ToString()=="")
            {
                MessageBox.Show("请选择一项进行删除");
            }
            else 
            {
                //判断用户是否点击确定按钮,true为点击,false为没有点击
                if (MessageBox.Show("确认删除?","提示", MessageBoxButtons.YesNo)==DialogResult.Yes)
                {
                    //定义数组,用循环赋值

                    String[] array = new String[];
                    for (int i = 0; i < this.dgv.SelectedRows.Count; i++)
                    {
                        String str = this.dgv.Rows[this.dgv.SelectedRows[i].Index].Cells[0].Value.To