How can I programmatically select every newly added row in a DataGridView?

jumexmango 136 Reputation points
2021-10-12T17:29:49.787+00:00

I have a button set up that adds a new row to my data grid.

I have tried
DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(0)

While this code does select every newly added row, it resets all my True's to False (I have check boxes that allow the user to change the columns between true and false). This only happens when this code is implemented.

EDIT: I just found out that it is only resenting the row previous to the newly added one.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,562 questions
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-10-14T02:03:49.817+00:00

    Hi @jumexmango ,
    I make a test on my side, and here's the result of my test.
    140404-gif.gif

    It seems that it does select every newly added row.
    Code of my test.

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
            DataGridView1.Rows.Add("row1", "2", 3.5, False, False)  
            DataGridView1.Rows.Add("cookie", "1", 4, False, True)  
            DataGridView1.Rows.Add("row2", "3", 4.5, True, False)  
            DataGridView1.Rows.Add("cookie", "1", 5.5, False, True)  
        End Sub  
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
            For Each row As DataGridViewRow In DataGridView1.Rows  
                If row.Cells(0).Value = "cookie" Then  
                    row.Cells(1).Value = Double.Parse(row.Cells(1).Value)  
                    row.Cells(2).Value = Double.Parse(row.Cells(2).Value)  
                End If  
            Next  
      
            Dim rowId As Integer  
            rowId = DataGridView1.Rows.Add("cookie", "1", 3.5, True, True)  
            DataGridView1.CurrentCell = DataGridView1.Rows(rowId).Cells(0)  
        End Sub  
    

    Please let me know if I have any misunderstanding.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 81,446 Reputation points
    2021-10-13T05:58:45.77+00:00

    You can do :

    bSelect = True
    ' Add your row here 
    

    then

        Private bSelect As Boolean = False
    
        Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
            If (bSelect) Then
                DataGridView1.Rows(e.RowIndex).Selected = True
                bSelect = False
            End If
        End Sub
    
    0 comments No comments