I am using VS 2008/C# and binding a local List of helper classes as the DataSource for a DataGridView control. Calling the Remove() method on my List of helper classes fires the CellFormatting event of the DataGridView, which makes sense (a bit).
When removing whatever happens to be the DataBoundItem of the last row in the grid (so long as the grid has more than one row) the DataGridView's Rows collection is not updated before this event fires. So, in the CellFormatting event handler, I get an IndexOutOfRangeException as the Rows collection is one too large.
I've tried removing the row using the DataGridView.Rows.Remove() method, and binding using a BindingSource rather than binding the List directly as the data source.
I found a few references to this occurance via Google, but answers were either not forthcoming or said to use a Delete() method on either the DataGridView or the DataGridView.Rows collection - neither of which currently exist.
Sorting does not appear to be the issue either, as performing/not performing a sort results in the same outcome.
The only exception to the "last row" being a problem for removal is if the DataGridView contains only one row - in which case everything works fine.
I've had this problem in the past, and if I remember correctly there's one of two things you can do. When you remove the record from the collection, set the datasource property on your datagridview to null, and then rebind it to your list. That should do the trick.
Alternatively, you can handle the DataError event on your dataGridview and in the method you can say e.Cancel = true to suppress the exception, or you can further deal with it there.
First just disable the property of Datagridview
as
dataGridView1.AllowUserToAddRows = false;
and then just remove the last rows as many rows as you want either with for loop by keeping -1.
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
To hide the last row, change the AllowUserToAddRows property of the datagridview as shown:
myDataGridView1.AllowUserToAddRows = false
I have the same problem. I have found a solution. Try to copy all the rows to next row. then remove the first row of dgv. A sample code for this:
If Dgv.CurrentCell.RowIndex + 1 = Dgv.Rows.Count Then
For m = Dgv.Rows.Count - 2 To 0 Step -1
Dgv.Rows(m + 1).Cells(0).Value = Dgv.Rows(m).Cells(0).Value
Dgv.Rows(m + 1).Cells(1).Value = Dgv.Rows(m).Cells(1).Value
Dgv.Rows(m + 1).Cells(2).Value = Dgv.Rows(m).Cells(2).Value
Dgv.Rows(m + 1).Cells(3).Value = Dgv.Rows(m).Cells(3).Value
Next
Dgv.Rows.RemoveAt(0)
Exit Sub
End If
Dgv.Rows.Remove(Dgv.CurrentRow)
try it:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With