本文介绍了搜索 DataGridView 并选择匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 DataGridView 的第一列中搜索值并选​​择存在值的行?-- 很像 SQL 中的 WHERE 子句.

How would I search a DataGridView's first column for a Value and select the row IF the Value is there? -- Much like a WHERE Clause in SQL.

我一直在线程中寻找答案,但似乎找不到.

I've been looking around for an answer in threads but I can't seem to find one.

DataGridView1 是 DataGridView,My.Settings.CurrentUserID 是我要搜索的值.

DataGridView1 is the DataGridView and My.Settings.CurrentUserID is the Value I want to search for.

任何帮助将不胜感激.

注意;表中的 Value 只能出现一次,因此不必担心多次返回/匹配.

Note; There can only be one occurrence of the Value in the table, so there is no concern for multiple returns/matches.

{编辑 1}

Steves 解决方案似乎只突出显示该行,而实际上并未选择它,因为黑色箭头不会移动到该行上.代码要查找的值是 4,注意它是如何找到并突出显示它的,但箭头不动.

Steves solution seems to only highlight the row and not actually select it as the Black arrow doesn't move onto it. The value the code's looking for is 4, notice how it finds it and highlights it, but the arrow doesn't move.

代码是这样做的:

我需要它来做到这一点:

推荐答案

那么假设您要搜索的列是第一个列

Well supposing that the column you want to search is the first one then

For Each row in DataGridView1.Rows
    If Convert.ToInt32(row.Cells(0).Value) = My.Settings.CurrentUserID Then
        row.Selected = True
        Exit For
    End If
Next

要指示当前"行,请设置 CurrentCell 数据网格视图的属性.

To indicate the "current" row, set the CurrentCell property of the datagridview.

   .....
   DataGridView1.CurrentCell = row.Cells(0)
   Exit For

来自 MSDN:

当您将一个单元格设置为当前单元格时,如果它当前未显示.当前单元格不能是标题单元格、禁用的单元格或隐藏的行或列中的单元格.

这篇关于搜索 DataGridView 并选择匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 03:14