Vb.net 使用文本框中的值在datagrid中搜索
如何在msgbox中显示值。在datagrid的第一列中,我根据textbox查找值,我希望显示第二列和msgbox中同一行的值。现在我只找到了一件东西 您可以直接通过枚举List2DataGridView.行。对于每个行,无需使用索引来访问它们Vb.net 使用文本框中的值在datagrid中搜索,vb.net,datagridview,datagrid,Vb.net,Datagridview,Datagrid,如何在msgbox中显示值。在datagrid的第一列中,我根据textbox查找值,我希望显示第二列和msgbox中同一行的值。现在我只找到了一件东西 您可以直接通过枚举List2DataGridView.行。对于每个行,无需使用索引来访问它们 For Each row As DataGridViewRow In List2DataGridView.Rows 然后,我们测试每一行的值,当我们找到匹配的行时,我们显示一条包含其值的消息。我们可以访问该值,因为它在范围内。当我们找到匹配的元素时,
For Each row As DataGridViewRow In List2DataGridView.Rows
然后,我们测试每一行的值,当我们找到匹配的行时,我们显示一条包含其值的消息。我们可以访问该值,因为它在范围内。当我们找到匹配的元素时,我们退出For Each
然而,这不是最优雅的解决方案,可读性差。具体地说,使用Exit For有点难看,并且使代码更难在同一个地方找到
我们可以通过使用LINQ做得更好
Dim Matches = From row As DataGridViewRow In List2DataGridView.rows
Let CellValue = row.Cells.Item(1).Value
Where CellValue = TextBox2.Text
Select New With {CellValue, row.Index}
Dim Match = Matches.FirstOrDefault()
If Match IsNot Nothing Then
MsgBox("Item is found in row: " & Match.Index)
MsgBox("Value of second column in this row: " & Match.CellValue)
End If
当您回答有关stackoverflow的任何问题时,请解释。@manu我编辑此内容是为了解释代码,并提供更可读的版本,但不确定它是否回答了问题,因为我发现问题的意图不清楚
For Each row As DataGridViewRow In List2DataGridView.Rows
For Each row As DataGridViewRow In List2DataGridView.Rows
If row.Cells.Item(1).Value = TextBox2.Text Then
MsgBox("Item is found in row: " & row.Index)
MsgBox("Value of second column in this row: " & row.Cells.Item(1).Value)
Exit For
End If
Next
MsgBox("Item not found")
Dim Matches = From row As DataGridViewRow In List2DataGridView.rows
Let CellValue = row.Cells.Item(1).Value
Where CellValue = TextBox2.Text
Select New With {CellValue, row.Index}
Dim Match = Matches.FirstOrDefault()
If Match IsNot Nothing Then
MsgBox("Item is found in row: " & Match.Index)
MsgBox("Value of second column in this row: " & Match.CellValue)
End If