vb.net DataGridView把多个HeaderText属性值写入数组获取多列单元格的字符串的多种方法,每行后面注释
时间: 2024-03-19 11:44:00 浏览: 96
1. 使用循环遍历每个指定的列,逐一将列的 HeaderText 属性值添加到数组中,再遍历每行获取多列单元格的字符串:
```
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 查询语句获取指定列的 HeaderText 属性值的数组,再使用 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. 使用 GetColumnHeaders 方法获取指定列的 HeaderText 属性值的数组,再使用 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
```
阅读全文