I am using C# .NET 2.0 Visual Studio 2005.
I am encountering weird issue.
There is a simple window form with just one DataGridView with column1 being checkbox (DataGridViewCheckboxColumn).
Then if the checkbox in the cell is checked, I want to remove the checked row.
Sound really simple but it does not remove all checked rows somehow, and I can't really figure why it is behaving in this way.
For instance, I have 5 rows and checked all checkbox in each row but it only removes 3 rows. Has anyone seen this before? Is this a bug or am I doing something wrong?
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//when I click the button, all checked row should be removed
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((bool)row.Cells[0].Value)
{
dataGridView1.Rows.Remove(row);
}
}
}
}
}
its happening when one row is removed the rows count decrements too so if you put your code in for loop and run it in reverse it would work fine have a look:
for (int i = dataGridView1.Rows.Count -1; i >= 0 ; i--)
{
if ((bool)dataGridView1.Rows[i].Cells[0].FormattedValue)
{
dataGridView1.Rows.RemoveAt(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With