vb.net DataGridView循环列,获取是否包含有指定字符串的列内容的多种方法,代码后面带备注
时间: 2024-03-17 17:42:16 浏览: 88
以下是几种获取DataGridView指定字符串列内容的方法,注释在代码中:
方法一:使用for循环遍历列和行,判断单元格内容是否包含指定字符串
```
Dim targetString As String = "指定字符串"
Dim targetColumns As List(Of Integer) = New List(Of Integer)()
For columnIndex As Integer = 0 To dataGridView1.Columns.Count - 1
For rowIndex As Integer = 0 To dataGridView1.Rows.Count - 1
If dataGridView1.Rows(rowIndex).Cells(columnIndex).Value.ToString().Contains(targetString) Then
' 如果包含指定字符串,将列索引加入List
targetColumns.Add(columnIndex)
Exit For ' 如果该列有单元格包含指定字符串,跳出该列的循环
End If
Next
Next
' targetColumns 中存储的是包含指定字符串的列的索引
```
方法二:使用LINQ查询,获取包含指定字符串的列
```
Dim targetString As String = "指定字符串"
Dim targetColumns As List(Of Integer) = (
From column As DataGridViewColumn In dataGridView1.Columns
Where (
From row As DataGridViewRow In dataGridView1.Rows
Where Convert.ToString(row.Cells(column.Index).Value).Contains(targetString)
Select row
).Any()
Select column.Index
).ToList()
' targetColumns 中存储的是包含指定字符串的列的索引
```
方法三:使用DataGridView控件的CellFormatting事件,获取包含指定字符串的列
```
Dim targetString As String = "指定字符串"
Dim targetColumns As List(Of Integer) = New List(Of Integer)()
Private Sub dataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dataGridView1.CellFormatting
If e.RowIndex = 0 Then ' 只在第一行格式化时判断列内容
If e.Value IsNot Nothing AndAlso e.Value.ToString().Contains(targetString) Then
targetColumns.Add(e.ColumnIndex)
End If
End If
End Sub
' targetColumns 中存储的是包含指定字符串的列的索引
```
阅读全文