vb.net DataGridView使用循环把多个列标题文本HeaderText写入数组获取多列单元格的字符串的多种方法,每行后面注释
时间: 2024-03-19 14:43:57 浏览: 61
DataGridView 实现一列单元格 显示多操作方式
1. 使用循环遍历每个指定的列,逐一将列标题文本添加到数组中,再遍历每行获取多列单元格的字符串:
```
Dim columnHeaders As New List(Of String)
For Each col As DataGridViewColumn In DataGridView1.Columns
If col.HeaderText = "Column1" OrElse col.HeaderText = "Column2" Then
columnHeaders.Add(col.HeaderText)
End If
Next
For Each row As DataGridViewRow In DataGridView1.Rows
Dim cellValues As New List(Of String)
For Each header In columnHeaders
Dim cellValue As String = row.Cells(header).Value.ToString()
cellValues.Add(cellValue)
Next
'处理多列单元格的字符串
Next
```
2. 使用 LINQ 查询语句获取指定列标题的数组,再使用 For Each 循环遍历每行获取多列单元格的字符串:
```
Dim columnHeaders = (From col As DataGridViewColumn In DataGridView1.Columns
Where col.HeaderText = "Column1" OrElse col.HeaderText = "Column2"
Select col.HeaderText).ToArray()
For Each row As DataGridViewRow In DataGridView1.Rows
Dim cellValues As New List(Of String)
For Each header In columnHeaders
Dim cellValue As String = row.Cells(header).Value.ToString()
cellValues.Add(cellValue)
Next
'处理多列单元格的字符串
Next
```
3. 使用 GetColumnCount 方法和 GetColumnHeaders 方法获取指定列标题的数组,再使用 GetCellValues 方法获取多列单元格的字符串:
```
Dim columnHeaders = DataGridView1.GetColumnHeaders().
Where(Function(h) h = "Column1" OrElse h = "Column2").ToArray()
Dim rowCount As Integer = DataGridView1.Rows.Count
Dim cellValues = DataGridView1.GetCellValues(0, 0, rowCount, columnHeaders.Length)
For Each rowValues In cellValues
Dim cellValuesArray = rowValues.Cast(Of String).ToArray()
'处理多列单元格的字符串
Next
```
阅读全文