Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove rows in data grid view where checkbox is checked?

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);
                }
            }
        }
    }
}
like image 598
Meow Avatar asked Jun 22 '11 12:06

Meow


1 Answers

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);
    }
}
like image 92
love Computer science Avatar answered Oct 13 '22 01:10

love Computer science