Click here to Skip to main content
14,880,436 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to delete multiple rows from datagridview but only one is deleting at a time. don't mind my codes as am testing it, haven't perfected it yet.

What I have tried:

C#
<pre>private void button2_Click(object sender, EventArgs e)
    {
        DataGridViewRow row = new DataGridViewRow();
        for (int i = 0; i < DataGrid1.Rows.Count; i++)
        {
            row = DataGrid1.Rows[i];
            if (Convert.ToBoolean(row.Cells[0].Value))
            {
                string Name = row.Cells[1].Value.ToString();
                string id = Convert.ToString(row.Cells[1].Value);
                //Delete_Row(id);
                try
                {
                    connect.Open(); //Open Connection  
                    SqlCommand cmd = new SqlCommand("DELETE FROM med WHERE Name =@Name", connect); //Here, we specify query with {Id} parameter which allow us to delete rows from Db.  
                    cmd.Parameters.AddWithValue("@Name", Name);
                    int Result = cmd.ExecuteNonQuery(); // Execute Query for deleting all rows selected from DataGridView  
                    connect.Close(); // Close Connection  
                    label6.Text = "Deleted Successfully.";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                this.BindDataGridView();
                DataGrid1.Rows.Remove(row);
                i--;
            }
        }
    }
Posted
Updated 3-Mar-21 6:36am

1 solution

You have a couple of issues here. First part of your problem is because you are also removing the datagrid rows using this for-loop
for (int i = 0; i < DataGrid1.Rows.Count; i++)
Say you had a grid with 3 rows in it
Row 1 : "1"
Row 2 : "2"
Row 3 : "3"
If you start at the top and delete row 1 you now get
Row 1 : "2"
Row 2 : "3"
So instead of looking at the "2" value your variable i is now pointing to the "3" value. Follow this through and you "fall off" the end of the grid, usually with an error.
Start your loop at the other end and work backwards
C#
for (int i = DataGrid1.Rows.Count -1; i >= 0; i--)
        {
...
                DataGrid1.Rows.Remove(row);
            }
        }
Next - why do you have
C#
i--;
I suspect this was an attempt to get over the problem I described above. You don't want to be changing your loop counter in that way.
Next, why use
C#
this.BindDataGridView();
inside the loop? This potentially also changes the position of data in your grid. Wait until you have deleted all the rows you want to get rid of and then rebind as a single step.

Lastly
C#
DataGridViewRow row = new DataGridViewRow();
You don't actually use that new row so why go to the expense of creating it?

I think your code should look more like this (warning, untested)
C#
private void button2_Click(object sender, EventArgs e)
    {
        for (int i =  DataGrid1.Rows.Count - 1; i >=; i--)
        {
            DataGridViewRow row = DataGrid1.Rows[i];
            if (Convert.ToBoolean(row.Cells[0].Value))
            {
                string Name = row.Cells[1].Value.ToString();
                string id = Convert.ToString(row.Cells[1].Value);
                //Delete_Row(id);
                try
                {
                    connect.Open(); //Open Connection  
                    SqlCommand cmd = new SqlCommand("DELETE FROM med WHERE Name =@Name", connect); //Here, we specify query with {Id} parameter which allow us to delete rows from Db.  
                    cmd.Parameters.AddWithValue("@Name", Name);
                    int Result = cmd.ExecuteNonQuery(); // Execute Query for deleting all rows selected from DataGridView  
                    connect.Close(); // Close Connection  
                    label6.Text = "Deleted Successfully.";
                    DataGrid1.Rows.Remove(row);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        this.BindDataGridView();
    }
I'm not going to pick up on the fact the connection seems to be defined outside this function entirely - in this instance I would probably open the connection outside the loop and close it in a finally statement or use a using statement. I would also give the button a meaningful name rather than the default "button2". All things for you to consider.
   
Comments
Member 13591430 3-Mar-21 17:21pm
   
Thank you very much, you just help a brother. my appreciation unlimitedly

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