如何通过列名从ObjectListView中获取单元格值
问题描述
我有一个ObjectListView网格,列信息如下(括号内是列名):
| Id (olvColumn1) | Unique Id (olvColumn2) | Parent Id (olvColumn3) | Name (olvColumn4) | Desc (olvColumn5) |
|---|---|---|---|---|
| 1003 | 1 | 7 | Name 1 | Test desc 1 |
| 1003 | 3 | 2 | Name 2 | Test desc 2 |
| 1003 | 4 | 5 | Name 3 | Test desc 3 |
| 1004 | 2 | 6 | Name 4 | Test desc 4 |
| 1004 | 5 | 9 | Name 5 | Test desc 5 |
我需要通过列名olvColumn2提取“Unique Id”列的单元格值,要求遍历整个网格逐行获取,不能用SelectedRows方法(当前无选中行)。目前我通过列索引实现了功能,但列在设计或运行时重排会导致取值错误,希望改用列名实现。现有代码如下:
Private Function GetRowNextUniqueId() As Integer Dim I As Integer Dim mytmpRowId As Integer Dim myUniqueRowId As Integer For Each itm As ListViewItem In dlvEstimate.Items mytmpRowId = Convert.ToInt32(itm.SubItems(0).Text) ' 这里itm.SubItems(0)不能传入列名,我想改成传入列名来获取对应列的值 If mytmpRowId > myUniqueRowId Then myUniqueRowId = mytmpRowId End If Next Return myUniqueRowId End Function
解决方案
方法1:通过列名获取当前显示索引取值
先从ObjectListView的列集合中找到名称为olvColumn2的列,获取它的DisplayIndex(列重排后这个值会自动更新,对应当前显示的位置),再用这个索引获取单元格内容:
Private Function GetRowNextUniqueId() As Integer Dim myUniqueRowId As Integer = 0 ' 查找目标列 Dim targetColumn As OlvColumn = dlvEstimate.Columns.Cast(Of OlvColumn)().FirstOrDefault(Function(c) c.Name = "olvColumn2") If targetColumn IsNot Nothing Then Dim columnIndex As Integer = targetColumn.DisplayIndex For Each itm As ListViewItem In dlvEstimate.Items ' 用TryParse避免格式错误导致异常 If Integer.TryParse(itm.SubItems(columnIndex).Text, Dim mytmpRowId As Integer) Then If mytmpRowId > myUniqueRowId Then myUniqueRowId = mytmpRowId End If End If Next End If Return myUniqueRowId End Function
方法2:直接操作绑定的数据源(更可靠)
ObjectListView的核心优势是绑定数据源,直接遍历数据源对象完全不受列顺序影响,是更推荐的做法:
假设你的数据源是自定义类集合(比如List(Of EstimateItem)),且EstimateItem类有对应“Unique Id”列的属性(比如UniqueId,同时要确保olvColumn2的AspectName属性设置为UniqueId),代码可以简化为:
Private Function GetRowNextUniqueId() As Integer Dim myUniqueRowId As Integer = 0 For Each item As EstimateItem In dlvEstimate.Objects If item.UniqueId > myUniqueRowId Then myUniqueRowId = item.UniqueId End If Next Return myUniqueRowId End Function
这种方式跳过了ListViewItem的层级,直接操作原始数据,完全不用担心列重排或显示索引变化的问题,维护性更强。
内容的提问来源于stack exchange,提问作者Pankaj
相关产品推荐
相关产品推荐

