简体   繁体   中英

Select cell in dataGridView by header text

I'm looping through rows in a datagridview, and selecting a cell from the 3rd column each time:

Dim customer_name as String
For Each dgvr As DataGridViewRow In myDataGridView.Rows
   customer_name= dgvr.Cells(2).Value
   '....
next dgvr

However, I'd really like to make it dynamic, in case a new column gets added to the grid, so that I need the 4th column, not the 3rd.

Ideally I'd like to use the column's header text. So something like...

customer_name= dgvr.Cells("Customer").value

Can this be done?

This code works well for selected cells under a specific column name. Maybe you can use it for what you're looking for. The best part is, it auto scrolls to the selected column.

This basically runs from a text box and a button. User can enter a string of text and hit the button, then it will go find the column. If no column exists, it tells you.

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
    Dim search As String = tbSearch.Text
    Dim Found As Integer = 0

    If dgv.Rows.Count > 0 Then
        For Each col As DataGridViewColumn In dgv.Columns
            Dim colname As String = col.HeaderText

            If search = colname Then
                'MsgBox(search & " = " & colname)
                dgv.Rows.Item(0).Cells(search).Selected = True
                Found = 1
            End If
        Next

        If Found = 1 Then
            'do nothing
        Else
            MsgBox("No columns with the name " & search)
        End If
    Else
        MsgBox("No data to analyze... ")
    End If
End Sub

This can be done, it is possible to select by header text. You can loop through each row and find the value for the name of a column.

For Each dgvr As DataGridViewRow In myDataGridView.Rows

Dim testString As String
testString = dgvr("Customer").ToString()

This should set the value of the test string to the current cell under the column name.

Hope this helps :)

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