vb.net DataGridView根据列标题文本获取对应列的全部文本各种方法,代码后面带注释
时间: 2024-03-17 22:46:07 浏览: 72
除了前面介绍的方法,还有其他几种方式可以根据列标题文本获取对应列的全部文本,以下是详细的代码示例和注释:
1. 使用 LINQ 查询:
```vb
' 使用 LINQ 查询获取某列文本
Private Function GetColumnTextWithLINQ(ByVal dgv As DataGridView, ByVal columnName As String) As List(Of String)
' 使用 LINQ 查询获取指定列的单元格文本
Dim columnText = (From row As DataGridViewRow In dgv.Rows
Where Not row.IsNewRow AndAlso row.Cells(columnName).Value IsNot Nothing
Select row.Cells(columnName).Value.ToString()).ToList()
Return columnText
End Function
```
使用示例:
```vb
' 获取 "姓名" 列的全部文本
Dim nameList As List(Of String) = GetColumnTextWithLINQ(dataGridView1, "姓名")
For Each name As String In nameList
Console.WriteLine(name)
Next
```
2. 使用 DataColumn 和 DataTable:
```vb
' 使用 DataColumn 和 DataTable 获取某列文本
Private Function GetColumnTextWithDataTable(ByVal dgv As DataGridView, ByVal columnName As String) As List(Of String)
' 创建 DataTable 对象,并添加与 DataGridView 列相同的 DataColumn
Dim dt As New DataTable()
For Each column As DataGridViewColumn In dgv.Columns
dt.Columns.Add(column.Name)
Next
' 将 DataGridView 中的数据复制到 DataTable 中
For Each row As DataGridViewRow In dgv.Rows
If Not row.IsNewRow Then
Dim newRow As DataRow = dt.Rows.Add()
For Each cell As DataGridViewCell In row.Cells
newRow(cell.ColumnIndex) = cell.Value
Next
End If
Next
' 获取指定列的单元格文本
Dim columnText = dt.AsEnumerable() _
.Where(Function(r) r.Field(Of String)(columnName) IsNot Nothing) _
.Select(Function(r) r.Field(Of String)(columnName)).ToList()
Return columnText
End Function
```
使用示例:
```vb
' 获取 "姓名" 列的全部文本
Dim nameList As List(Of String) = GetColumnTextWithDataTable(dataGridView1, "姓名")
For Each name As String In nameList
Console.WriteLine(name)
Next
```
3. 使用 BindingSource:
```vb
' 使用 BindingSource 获取某列文本
Private Function GetColumnTextWithBindingSource(ByVal dgv As DataGridView, ByVal columnName As String) As List(Of String)
' 创建 BindingSource 对象,并将 DataGridView 绑定到该对象
Dim bs As New BindingSource()
bs.DataSource = dgv.DataSource
bs.DataMember = dgv.DataMember
' 获取指定列的单元格文本
Dim columnText = (From row As DataRowView In bs.List
Where row(columnName) IsNot Nothing
Select row(columnName).ToString()).ToList()
Return columnText
End Function
```
使用示例:
```vb
' 获取 "姓名" 列的全部文本
Dim nameList As List(Of String) = GetColumnTextWithBindingSource(dataGridView1, "姓名")
For Each name As String In nameList
Console.WriteLine(name)
Next
```
注意事项:
- 如果列标题文本不存在,则会抛出异常。
- 如果单元格的值为 null,则不会将其添加到列表中。如果需要包含 null 值,可以将 `cell.Value.ToString()` 更改为 `If(cell.Value Is Nothing, "", cell.Value.ToString())` 或 `row(columnName)?.ToString()`。
阅读全文