Search code examples
vb.netwinformsdatagridviewvisual-studio-2005delete-row

How to remove a row from datagridview and reset a particular column (vb.net 2005)


I am using VS 2005 edition. I am developing a winform desktop application. Let's say I have a unbound datagridview, with table like below:

Original datagrid before delete:

original datagrid before delete

If I removed Stuff D (Item No 5), the "Item No" column supposed to reset itself accordingly. The expected output should be:

After delete row:

after delete row

The "Item No" column is not an autonumber, it's just the number I assigned incrementally as the user add in a new row(new Stuff). I tried using the following code in rowremoved event but failed to achieve the expected output. Please help. Thanks.


Solution

  • If the goal is just showing the record index in cell, then you don't need to assign a value to cell and it's enough to set e.Value = e.RowIndex + 1 in CellFormatting event.

    But based on your comment it seems you need those cells have values as well. So you need to handle RowsRemoved and RowsAdded event of DataGridView and refresh the cell value with row number:

    Public Sub RefreshRowNumbers(g As DataGridView)
        For Each r As DataGridViewRow In g.Rows
            r.Cells(1).Value = r.Index + 1
        Next
    End Sub
    
    Private Sub DataGridView1_RowsRemoved(sender As Object, _
        e As DataGridViewRowsRemovedEventArgs) Handles DataGridView1.RowsRemoved
        RefreshRowNumbers(DirectCast(sender, DataGridView))
    End Sub
    
    Private Sub DataGridView1_RowsAdded(sender As Object, _
        e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
        RefreshRowNumbers(DirectCast(sender, DataGridView))
    End Sub