Shiblee Marsuik
Shiblee Marsuik

Reputation: 43

Deleting ALL selected rows from datagridview

I am using datagridview to view a SQL Table on Windows Form and I was hoping to use this to be able to add/delete rows from the SQL table.

I am using the following code to delete the selected rows from the datagridview:

        try
        {
            int count = dataGridView.SelectedRows.Count;

            foreach (DataGridViewRow item in dataGridView.SelectedRows)
            {
                TA.DeleteQuery(item.Cells[0].Value.ToString());
            }
        }
        catch (Exception ex) { Logs.LogEvent(3, ex.Message + "\n" + ex.ToString()); }
        finally { UpdateTable(); }

This code deletes all rows except the first row that is selected. When I step through the code the dataGridView selected rows count keeps displaying one less than the value selected which is what I expected but the foreach loop only iterates through 3 times. When I used a for loop to iterate through 4 times it gave me an out of range error!

Have you guys any idea why this might be and if there is a better way to approach this?

Let me know if you need more details.

Thanks in advance guys!

Upvotes: 0

Views: 209

Answers (1)

Shiblee Marsuik
Shiblee Marsuik

Reputation: 43

The problem may have been a bug on the version of the visual studio that I was using. When I upgraded the version to 15.5.7 (I can't remember what version it was before) the problem has disappeared. This may be the reason why others could not reproduce this problem.

It was something that I had at the back of my mind all the time but I wanted to exhaust all my other options.

Upvotes: 1

Related Questions