vb.net - 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当它找到但它并没有真正被选中,它和你点击它不一样。例如,我有一个按钮正在更改选定行的背景颜色,搜索后,它会为开头选择的第一行着色。
如何改变它?谢谢你。
解决方案
我刚刚测试过,它确实按照您描述的方式工作。我使用了这段代码:
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
推荐阅读
- selenium - 进程意外关闭,状态为 1
- spring-boot - Spring Boot Project Jar 文件未读取放置在类路径上的文件
- android - 画布油漆,贝塞尔曲线,弧最高点
- django - Django文件上传:完整性错误
- java - Logback 不会关闭 dbappender 的数据源连接
- e-commerce - 从需求软件导出库存数据并将订单数据导入需求软件
- python-3.x - 在django中给出电子邮件时如何从数据库中找到用户的用户名
- python-3.x - 计算python中多维列表中每个字符的出现次数
- datasource - 带有 Athena 自定义查询的 Tableau 数据源
- python - 熊猫 DataFrame.copy(deep=False) 的目的?