首页 > 解决方案 > VB row.Cells("XX").Selected = True 没有真正被选中

问题描述

我想在搜索过程中选择行:代码:

Private Sub TextBoxSEARCH_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBoxSEARCH.TextChanged
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.Cells("Column1").Value = TextBoxSEARCH.Text Then
            DataGridView1.ClearSelection()
            row.Cells("Column1").Selected = True
            Exit For
        End If
    Next
End Sub

一切正常,它也!显示!me right row当它找到但它并没有真正被选中,它和你点击它不一样。例如,我有一个按钮正在更改选定行的背景颜色,搜索后,它会为开头选择的第一行着色。

如何改变它?谢谢你。

标签: vb.netwinformsdatagridview

解决方案


我刚刚测试过,它确实按照您描述的方式工作。我使用了这段代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim table As New DataTable

    With table.Columns
        .Add("Id", GetType(Integer))
        .Add("Name", GetType(String))
        .Add("DoB", GetType(Date))
    End With

    With table.Rows
        .Add(1, "Peter", #6/19/1969#)
        .Add(2, "Paul", #1/1/2000#)
        .Add(3, "Mary", #5/3/2021#)
    End With

    BindingSource1.DataSource = table
    DataGridView1.DataSource = BindingSource1
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    DataGridView1.ClearSelection()

    Dim matchingRow = DataGridView1.Rows.
                                    Cast(Of DataGridViewRow).
                                    FirstOrDefault(Function(dgvr) CStr(dgvr.Cells(1).Value) = TextBox1.Text)

    If matchingRow IsNot Nothing Then
        matchingRow.Selected = True
    End If
End Sub

它完全按预期工作。如果你没有看到,那么要么你的系统坏了,要么你实际上没有匹配文本。请记住,您正在进行区分大小写的相等比较,因此您必须匹配大小写以及文本的字母。如果这不是您想要的,那么您需要一个不区分大小写的比较:

FirstOrDefault(Function(dgvr) CStr(dgvr.Cells(1).Value).Equals(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase))

编辑:

首先,如果SelectionMode设置为FullRowSelect那么您可以选择任一行:

matchingRow.Selected = True

或一个单元格:

matchingRow.Cells(1).Selected = True

NullReferenceException其次,如果网格包含数据输入行,我展示的不区分大小写的比较将抛出 a ,因为单元格Value将是Nothing,因此Equals不能在其上调用。为了解决这个问题,比较必须更复杂一点:

Dim matchingRow = DataGridView1.Rows.
                                Cast(Of DataGridViewRow).
                                FirstOrDefault(Function(dgvr)
                                                   Dim result = CStr(dgvr.Cells(1).Value)?.Equals(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase)

                                                   Return result.HasValue AndAlso result.Value = True
                                               End Function)

最后,问题实际上与选择无关,实际上是如何使匹配行成为当前行,这需要将该行中的单元格设为当前单元格。这取决于您要将插入符号放入哪个单元格。我认为是第一个单元格或执行比较的单元格,但可能有理由使用不同的单元格:

If matchingRow IsNot Nothing Then
    matchingRow.Cells(1).Selected = True
    DataGridView1.CurrentCell = matchingRow.Cells(1)
End If

推荐阅读