[英]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: 我正在遍历datagridview中的行,并每次都从第三列中选择一个单元格:
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. 但是,如果要向网格中添加新列,我真的很想使其动态化,因此我需要第4列,而不是第3列。
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 :) 希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.