2017-07-04 49 views
0

如何在msgbox中顯示值。在數據網格的第一列是基於文本框來查看值,我希望從第二列顯示值和msgbox中的同一行。現在,我只有「項目找到」使用文本框中的值在d​​atagrid中搜索

Here are columns

Private Sub PictureBox12_Click(sender As Object, e As EventArgs) Handles PictureBox12.Click 


     Dim temp As Integer = 0 
     For i As Integer = 0 To List2DataGridView.RowCount - 1 
      For j As Integer = 0 To List2DataGridView.ColumnCount - 1 
       If List2DataGridView.Rows(i).Cells(j).Value.ToString = TextBox2.Text Then 
        MsgBox("Intem found") 
        temp = 1 
       End If 
      Next 
     Next 
     If temp = 0 Then 
      MsgBox("Item not found") 
     End If 
    End Sub 

回答

0
Private Sub PictureBox12_Click(sender As Object, e As EventArgs) Handles PictureBox12.Click 

     Dim barcode As String 
     Dim rowindex As String 
     Dim found As Boolean = False 
     barcode = InputBox("Naskenujte čárový kód ||||||||||||||||||||||||||||||||||||") 
     If Len(Trim(barcode)) = 0 Then Exit Sub 'Pressed cancel 

     For Each row As DataGridViewRow In List2DataGridView.Rows 
      If row.Cells.Item("DataGridViewTextBoxColumn1").Value = barcode Then 
       rowindex = row.Index.ToString() 
       found = True 
       Dim actie As String = row.Cells("DataGridViewTextBoxColumn2").Value.ToString() 
       MsgBox("Čárový kód: " & barcode & vbNewLine & "Číslo dílu je: " & actie, , "Vyhledání dílu") 

       Exit For 
      End If 
     Next 
     If Not found Then 
      MsgBox("Item not found") 
     End If 
    End Sub 
0

您可以枚舉直接通過For EachList2DataGridView.Rows,就沒有必要使用索引來訪問它們。

For Each row As DataGridViewRow In List2DataGridView.Rows 

然後,對於每一行我們測試它的值,當我們找到匹配的行時,我們顯示一個包含它的值的消息。我們可以獲得價值,因爲它在範圍內。當我們找到匹配的元素,我們退出For Each

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") 

然而,這還不是最優雅的解決方案,並從可讀性差困擾。具體來說,使用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 
+3

當你在stackoverflow上回答任何問題時,請解釋一下。 –

+0

@manu我編輯這個解釋代碼,並提供一個更可讀的版本,不知道它是否回答這個問題,但因爲我發現問題的意圖不清楚 –

相關問題