如何从datagridview中删除被检查为false的行

时间:2022-03-21 15:28:09

I am new to c#. I am trying to import some data from excel sheet and then i displayed it in datagridview like this

我是c#新手。我试图从excel表中导入一些数据,然后在datagridview中显示它。

  OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select email from [" + loadtextfeild.Text + "$] where email like '%@%'     ", conn);
  DataTable dt = new DataTable();
  Excel.Application excel = new Excel.Application();
  Excel.Workbook wb = excel.Workbooks.Open(opentextfeild.Text);
  myDataAdapter.Fill(dt);
  displayviewgrid.DataSource = dt;
  wb.Close();

I have button in the form through which i can delete the unchecked rows. This buttons does now work properly.For example If there are 10 rows and these all are unchecked and now i press the button then the all rows should be deleted but it does delete all the rows. it deletes some of them then again i pressed it and then again it deletes rest of them. For checked values it works fine it does not delete them but for more than one unchecked values it is not working properly. It is not deleting them all at once. Here is the code

在表单中有一个按钮,可以通过它删除未检查的行。这个按钮现在可以正常工作了。例如,如果有10行这些都是未选中的现在我按下按钮那么所有的行都应该被删除但是它确实删除了所有的行。它删除了其中的一些然后我再次按下它又删除了其余的。对于已检查的值,它可以正常工作,它不会删除它们,但对于多个未检查的值,它不能正常工作。它并不是一下子把它们全部删除。这是代码

 foreach (DataGridViewRow roww in displayviewgrid.Rows)
  {               
    if (Convert.ToBoolean(roww.Cells[Column1.Name].Value) == false)
      {
        displayviewgrid.Rows.Remove(roww);// MessageBox.Show( "sadas"); 
      }              
  }

The foreach loop stops automatically after some iterations and it does not run till the last that's why i am unable to delete all the rows. I don't know why it's happening

foreach循环在一些迭代之后自动停止,直到最后一个循环才运行,这就是为什么我不能删除所有的行。我不知道为什么会这样

1 个解决方案

#1


1  

Replace ur remove row code with this code:

用以下代码替换删除行代码:

foreach (var roww in displayviewgrid.Rows.Cast<DataGridViewRow>().ToArray())
{               
   if (Convert.ToBoolean(roww.Cells[Column1.Name].Value) == false)
       displayviewgrid.Rows.Remove(roww);// MessageBox.Show( "sadas");               
}

Reason: You can not change collection in foreach loop, make copy of collection in loop.

原因:您不能在foreach循环中更改集合,在循环中复制集合。

More info: http://www.dotnetperls.com/invalidoperationexception

更多信息:http://www.dotnetperls.com/invalidoperationexception。

#1


1  

Replace ur remove row code with this code:

用以下代码替换删除行代码:

foreach (var roww in displayviewgrid.Rows.Cast<DataGridViewRow>().ToArray())
{               
   if (Convert.ToBoolean(roww.Cells[Column1.Name].Value) == false)
       displayviewgrid.Rows.Remove(roww);// MessageBox.Show( "sadas");               
}

Reason: You can not change collection in foreach loop, make copy of collection in loop.

原因:您不能在foreach循环中更改集合,在循环中复制集合。

More info: http://www.dotnetperls.com/invalidoperationexception

更多信息:http://www.dotnetperls.com/invalidoperationexception。