简体   繁体   中英

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:

删除之前的原始数据网格

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:

删除行后

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM