Search code examples
vb.netloopsforeachdatagridrow

How can i read the row in dgv vb net?


Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    TextBox2.Text = DataGridView1.Item(0, DataGridView1.CurrentRow.Index).Value
    Call connect()
    Dim str As String

    For Each rows As DataGridViewRow In DataGridView1.Rows
        str = "select *from Pr_MasterItem where item_id= '" & TextBox2.Text & "'"
        ListBox1.Items.Add("ada")
        Cmd = New SqlCommand(str, conn)
        Rd = Cmd.ExecuteReader
        Rd.Read()

        If Rd.HasRows Then
            TextBox4.Text = Rd.Item("item_id")
        Else
            ListBox1.Items.Add("Kosong")
        End If
    Next
    conn.Close()
End Sub

This code must be read row per row in datagrid and so in database.


Solution

  • You don't use rows inside the loop so what's the point of it? The idea of a For Each loop is that you do something for each item in the list, but you're not. You just using the current row, i.e. the row containing the caret, over and over.

    For Each row As DataGridViewRow In DataGridView1.Rows
        str = $"SELECT * FROM Pr_MasterItem WHERE item_id = '{row.Cells(0).Value}'"
    

    Note that I have changed the variable from rows to row, given that it contains a single row at a time. I have also ignored other issues with the code not specifically related to the issue, e.g. you should be using parameters rather than using string concatenation to build that SQL code.