LabRat
LabRat

Reputation: 2014

Search in column datagridview return value coresponding value datadgridview vb.net

I have a datagridview in vb.net with three columns. In the first column, a product description, in the second column there is a product number and in the third column, a price is given.

I would like to search in a datagridview by product number and return the corresponding value in the prices column.

I can to search for text in datagridviews, but I can't read the value of a corresponding cell such as the price cell.

Private Sub Button33_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button33.Click
    Dim rowindex As String
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.Cells.Item("ITEM_ID").Value = TextBox5.Text Then
            rowindex = row.Index.ToString()

            Dim actie As String = row.Cells("PRICE").Value.ToString()
            MsgBox(actie)

        Else

            MsgBox("Item not found")

        End If
    Next
End Sub

Upvotes: 0

Views: 39258

Answers (2)

Sachin Mohite
Sachin Mohite

Reputation: 11

It works for me. Try this:

If TextBoxSearch.Text IsNot Nothing Then
    Dim IsItemFound As Boolean = False
    Dim ItemPrice As String
    DataGridView1.ClearSelection()
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.Cells("ItemId").Value.ToString = TextBoxSearch.Text Then
            IsItemFound = True
            ItemPrice = row.Cells("ItemPrice").Value.ToString()
            row.Selected = True
            DataGridViewDetails.FirstDisplayedScrollingRowIndex = row.Index
            Exit For
        End If

        If Not IsItemFound Then
            MsgBox("Item not found")
        End If
    Next
End If

Upvotes: 1

WozzeC
WozzeC

Reputation: 2660

Allright, thanks for the code update. Do this:

Private Sub Button33_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button33.Click
    Dim rowindex As String
    Dim found as Boolean = false
    For Each row As DataGridViewRow In DataGridView1.Rows
        If row.Cells.Item("ITEM_ID").Value = TextBox5.Text Then
            rowindex = row.Index.ToString()
            found = true
            Dim actie As String = row.Cells("PRICE").Value.ToString()
            MsgBox(actie)
            Exit for
        End If
    Next
    If Not found Then
       MsgBox("Item not found")
    End if    
End Sub

What this does is that it loops through all the items. When it finds a match it sets found to true. If not item is found then "found" is false when the loop ends. And if "found" is false then you display "Item not found". Hope you understand, otherwise ask :)

Upvotes: 5

Related Questions