Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my problem when I select 3 selected rows from gridview using checkboxes remove 2 rows and the last row don't remove
what's the solution?
I write this class
C#
 public static bool DeletePayments(int id)
{                     
       bool b;

       string strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\Salaries.accdb";
       OleDbConnection conn = new OleDbConnection(strconn);

       if (conn.State == ConnectionState.Closed)
       {
              conn.Open();
       }

       OleDbCommand cmd = new OleDbCommand("DELETE FROM Payments WHERE Payment_ID =@id;", conn);

      cmd.Parameters.Add(new OleDbParameter("@id", id));

       int i = cmd.ExecuteNonQuery();

       if (i <= 0)
              b = false;
       else
              b = true;
       conn.Close();
       return b;
}

and at button_click event I write
C#
private void button3_Click(object sender, EventArgs e)
{
       for (int i = 0; i < GridViewPays.Rows.Count; i++)
       {
              if (GridViewPays.Rows[i].Cells[0].Value != null)
              {
                     if ((bool)GridViewPays.Rows[i].Cells[0].Value == true)
                     {
                            GridViewPays.Rows.RemoveAt(i);

                            if (PaymentsMgr.DeletePayments(int.Parse(GridViewPays.CurrentRow.Cells["Payment_ID"].Value.ToString())))
                            {
                                   GridViewPays.EndEdit();
                            }
                     }
              }
       }
}
Posted
Updated 31-Jul-14 4:45am
v2

1 solution

The problem is because you have started at the "beginning" of the gridview's rows with
C#
for (int i = 0; i < GridViewPays.Rows.Count; i++)

Say your DGV has 4 rows :
0  Row 1
1  Row 2
2  Row 3
3  Row 4

If you delete the first row (index = 0) the DGV will have to "shuffle" the remaining rows upwards - like this:
0  Row 2
1  Row 3
2  Row 4

So your loop moves onto its next value (index = 1) and deletes what was Row 3 and the rest get shuffled up.
0  Row 2
1  Row 4

When deleting from lists / grids / etc, if you are going to use the index of an item in a loop, always start at the bottom of the list and work upwards (or backwards). That way the rows do not get shuffled upwards, they stay where they were originally. E.g.
C#
for (int i = GridViewPays.Rows.Count; i >= 0; i--)
 
Share this answer
 

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



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