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

DataGridView 中删除一空行,出错
Gr中可edit ,这样中必然会出现所有可见列都为空值的,我想在某行失去焦点时,进行判断,如空则删除,用dataGridView1_RowLeave事件,但出错信息为:不能在此事件中执行操作。高手请教,该怎做?

private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
  {
  bool flag = true;
   
  for (int i = 0; i < dataGridView1.ColumnCount; i++)
  {
  if (dataGridView1.Rows[e.RowIndex].Cells[i].Value.ToString ().Trim ()=="")
  flag = true;
  else

  { flag = false;
  break; 
  }

  }
  if (flag&&(e.RowIndex!=this.dataGridView1.Rows.Count-1 ))//最后一行,不删
  {

  try
  {
  this.dataGridView1.Rows.Remove(this.dataGridView1.Rows[e.RowIndex]);//有问题
  //this.dataGridView1.Rows.RemoveAt(e.RowIndex);
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message.ToString()+"kkk"+e.RowIndex.ToString ());
   
  }

  }
  }

------解决方案--------------------
只是个思路,lz可以试下
C# code
        DataTable dt;
        private void Form1_Load(object sender, EventArgs e)
        {
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("id"));
            dt.Columns.Add(new DataColumn("name"));

            DataRow dr = null;
            dr = dt.NewRow();
            dr["id"] = "001";
            dr["name"] = "Name1";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = "002";
            dr["name"] = "Name2";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = "001";
            dr["name"] = "Name1";
            dt.Rows.Add(dr);

            //dt.TableNewRow += new DataTableNewRowEventHandler(dt_NewTableRow);
            dataGridView1.DataSource = dt;
        }
        bool flag = true;
        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (flag == false)
                dt.Rows.RemoveAt(e.RowIndex);
            flag = false;

        }

------解决方案--------------------
应该尽量从客户端控制其写入数据库中的数据的有效性!