You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取DataGridView中所有单元格的地址/引用?

问题:获取DataGridView所有匹配值的单元格地址并复用存储

这是某论坛线程的续帖,此前需求是根据单个单元格值获取对应DataGridView单元格地址,现在需要获取DataGridView中所有匹配指定数字的单元格地址/引用。

示例

示例表格:
6 9 7
8 1 5
2 4 3

期望输出:
6 is in cell (0,0)
9 is in cell (0,1)
7 is in cell (0,2)
8 is in cell (1,0)
1 is in Cell (1,1)
5 is in Cell (1,2)
2 is in Cell (2,0)
4 is in cell (2,1)
3 is in cell (2,2)

当前实现与问题

数字列表定义

创建了目标搜索数字列表:

Dim numbers As String() = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}

遇到的错误

  • 尝试添加单元格信息到列表时,代码cellsList.Add($"", i & ({cell.RowIndex}, {cell.ColumnIndex}))存在语法错误。
  • 使用Tuple存储数字时:
    Dim tpleNumbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8, 9)
    
    报错:Overload resolution failed because no accesible 'Create accepts this number of Arguments,推测Tuple最多支持8个元素。

现有代码状态

现有代码能按顺序输出匹配单元格的坐标,但无法同时显示对应单元格的值:

Dim cells = mulitpleGetCellAddress(DataGridView1, numbers.Select(Function(n) $"{n}"))
If cells IsNot Nothing Then
    MessageBox.Show($"Data exists in cells {String.Join("; ", cells.Select(Function(c) $"({c.RowIndex}, {c.ColumnIndex})"))}")
Else
    MessageBox.Show("Data does not exist!")
End If

Private Iterator Function mulitpleGetCellAddress(dgv As DataGridView, searchStrings As IEnumerable(Of String)) As IEnumerable(Of DataGridViewCell)
        For Each row In dgv.Rows.OfType(Of DataGridViewRow)
            For Each cell In row.Cells.OfType(Of DataGridViewCell)
                If searchStrings.Any(Function(s) cell.Value.ToString() = s) Then Yield cell
            Next
        Next
    End Function 

疑问

  1. 如何修改代码,实现显示所有匹配数字对应的单元格地址(格式如示例输出)?
  2. 是否需要调整数字列表的顺序才能实现预期输出?
  3. 获取到单元格地址后,想在多个DataGridView中复用,应该用List还是Array存储?

内容的提问来源于stack exchange,提问作者SsD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:22:04