Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I am using checkboxes inside Datagridview to select rows. While checking the value of checkbox its returning true, but I am trying to remove selected rows means its not working for some rows. Please see the codes I used.Please help me..

C#
private void BtnFill_Click(object sender, EventArgs e)
{
    for (int i = 1; i < 11; i++)
    {
        Dgv.Rows.Add(true, i, "name");
    }
}

private void BtnGet_Click(object sender, EventArgs e)
{
    string line = "Sl.No. "+ " ===== " + " Value " + "=====" + "EditedFormatedValue" + "\n";

    foreach (DataGridViewRow row in Dgv.Rows)
    {
        line += row.Cells[1].Value.ToString() + " ===== " + Convert.ToBoolean(row.Cells[0].Value) + "=====" + Convert.ToBoolean(row.Cells[0].EditedFormattedValue) + "\n";

    }
    MessageBox.Show(line);
}

private void button1_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in Dgv.Rows)
    {
        if (Convert.ToBoolean(row.Cells[0].Value))
        {
            Dgv.Rows.Remove(row);
        }

    }
    Dgv.Update(); Dgv.Refresh();
}

Thanks in Advance..
Posted

1 solution

You are modifying collection from which you are deleting, try following in button1_Click:
C#
List<DataGridViewRow> rowsToRemove = new List<DataGridViewRow>();
foreach (DataGridViewRow row in Dgv.Rows)
{
    if (Convert.ToBoolean(row.Cells[0].Value))
    {
        rowsToRemove.Add(row);
    }
}
rowsToRemove.ForEach(row => Dgv.Rows.Remove(row));
 
Share this answer
 
v2
Comments
Manu Prasad 9-Oct-14 5:05am    
Thanks!!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900