简体   繁体   中英

DataGridView Select Row with Specific Cell value [VB.NET]

I am using this code to move the row selection programmatically

            For Each row In DataGridView1.Rows()
                If row.Cells(0).Value.ToString().Equals(code) Then
                    row.Selected = True
                End If
                Exit For
            Next

But the Problem I am facing is This only Changes the highlighted row but doesn't actually select the row.. When I try to get data from selected row it gives data from previous row not the blue highlighted row. Actually Row header Tick type thing doesn't move It stays on previous row.

You also have to set the selceted cell:

 For Each row As DataGridViewRow In DataGridView1.Rows()
       If row.Cells(0).Value.ToString().Equals(code) Then
          row.Selected = True
          DataGridView1.CurrentCell = row.Cells(0)
          Exit For
      End If
 Next

The reason your code works only for the first row is that Exit For was outside the If statement. If you include it the code works like a charm.

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