Как выполнить поиск из TextBox и заполнить определенные столбцы DataGridView из базы данных SQL? - PullRequest
0 голосов
/ 24 ноября 2018

Я пытаюсь выполнить поиск по номеру товара, указанному в TextBox1.Я вручную создал заголовки в конструкторе для DataGridView.Мой код успешно запрашивает базу данных, но добавляет дополнительные столбцы к полным результатам, возвращаемым запросом.

Мой код:

Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click

    On Error Resume Next

    Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
        Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = @itemcode;", cn)

            cmd2.Parameters.AddWithValue("@itemcode", TextBox1.Text)
            cn.Open()

            Dim dr As SqlDataReader = cmd2.ExecuteReader()
            dt.Load(dr)

            DataGridView1.DataSource = dt

            For Each row As DataGridViewRow In DataGridView1.Rows
                cmd2.Parameters.Add("@item", SqlDbType.VarChar)
                cmd2.Parameters.Add("@qty", SqlDbType.VarChar)
                cmd2.Parameters.Add("@weight", SqlDbType.VarChar)

                With cmd2
                    row.Cells(1).Value = .Parameters("@item").Value
                    row.Cells(2).Value = .Parameters("@qty").Value
                    row.Cells(2).Value = .Parameters("@weight").Value
                End With
                cmd2.ExecuteNonQuery()
            Next
        End Using
    End Using
End Sub

1 Ответ

0 голосов
/ 24 ноября 2018

Уверен, что вы пытаетесь достичь чего-то подобного.Но, как отмечают другие, есть лучшие способы на самом деле связать ваши данные с сеткой.

    Try
        Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
            Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = @itemcode;", cn)

                cmd2.Parameters.AddWithValue("@itemcode", TextBox1.Text)
                cn.Open()

                Dim dr As SqlDataReader = cmd2.ExecuteReader()

                'Read each line
                While dr.Read()

                    Using record As New DataGridViewRow

                        'Get the individual items you want to return
                        Dim item As New DataGridViewTextBoxCell With {.Value = dr.GetValue(dr.GetOrdinal("item"))}
                        Dim qty As New DataGridViewTextBoxCell With {.Value = dr.GetValue(dr.GetOrdinal("qty"))}
                        Dim weight As New DataGridViewTextBoxCell With {.Value = dr.GetValue(dr.GetOrdinal("weight"))}

                        'Add each of those cells to the row
                        record.Cells.Add(item)
                        record.Cells.Add(qty)
                        record.Cells.Add(weight)

                        'Add the entire row to the DataGridView
                        DataGridView1.Rows.Add(record)
                    End Using
                End While
            End Using
        End Using
    Catch ex As SqlException
        Console.WriteLine(ex)
    End Try
...