【问题标题】:Select cell in dataGridView by header text通过标题文本选择dataGridView中的单元格
【发布时间】:2012-02-29 12:10:01
【问题描述】:

我正在遍历数据网格视图中的行,每次都从第三列中选择一个单元格:

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

但是,我真的很想让它动态化,以防新列被添加到网格中,所以我需要第 4 列,而不是第 3 列。

理想情况下,我想使用列的标题文本。所以像......

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

这个可以吗?

【问题讨论】:

  • 你不能只使用列名而不是标题文本吗?
  • 我的列名是空的。我通过将数据源设置为 System.Collections.Generic.List(Of Object) 来填充网格。

标签: vb.net datagridview


【解决方案1】:

此代码适用于特定列名下的选定单元格。也许你可以将它用于你正在寻找的东西。最好的部分是,它会自动滚动到选定的列。

这基本上是从一个文本框和一个按钮运行的。用户可以输入一串文本并点击按钮,然后它会找到该列。如果不存在列,它会告诉您。

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

【讨论】:

    【解决方案2】:

    可以这样做,可以通过标题文本进行选择。您可以遍历每一行并找到列名的值。

    For Each dgvr As DataGridViewRow In myDataGridView.Rows
    
    Dim testString As String
    testString = dgvr("Customer").ToString()
    

    这应该将测试字符串的值设置为列名下的当前单元格。

    希望这会有所帮助:)

    【讨论】:

    • 我收到以下错误:'System.Windows.Forms.DataGridViewRow' cannot be indexed because it has no default property.
    • 如果此列中没有信息,则会引发异常。如果有,请尝试使用 DataRow 而不是 DataGridViewRow。
    • 这是编译时错误,不是运行时错误,因此与列中的数据无关。使用数据行会产生运行时错误"Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Data.DataRow'."
    猜你喜欢
    • 1970-01-01
    • 2023-02-10
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多