从SQL Server在vb.net中的datagridview中添加行

时间:2017-02-17 02:07:01

标签: vb.net winforms datagridview

我在这里面临一个问题,下面的代码没有错误,但是我想从SQL Server中获取数据并在datagridview中添加行而不是在文本框中显示然后添加到datagridview。

Private Sub TextBox2_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
    If e.KeyCode = Keys.Enter Then
        'searchcproduct
        con = connection()

        con.Open()
        cmd.Connection = con
        cmd.CommandText = " select * from product  where plucode='" & TextBox2.Text & "' or barcode='" & TextBox2.Text & "'"
        Dim dbreader As SqlDataReader = cmd.ExecuteReader
        If dbreader.HasRows = False Then
            TextBox2.Text = ""
            TextBox2.Focus()
            itemnotfound.Show()
            PlayBackgroundSoundFile1()
        ElseIf dbreader.HasRows = True Then
            While dbreader.Read()
                TextBox4.Text = dbreader.Item("plu_description")
                TextBox5.Text = dbreader.Item("unitprice")
                TextBox7.Text = dbreader.Item("plu_qty")
                TextBox8.Focus()
            End While

        End If
    End If
    'TextBox2.Text = ""

End Sub

Private Sub Button20_Click(sender As System.Object, e As System.EventArgs) Handles Button20.Click
    Dim rowNumber As Integer = DataGridView1.Rows.Add()
    Try
        DataGridView1.Rows.Item(rowNumber).Cells(0).Value = Me.TextBox2.Text ' i want to display sql rather than textbox
        DataGridView1.Rows.Item(rowNumber).Cells(1).Value = Me.TextBox4.Text
        DataGridView1.Rows.Item(rowNumber).Cells(2).Value = Me.TextBox5.Text
        DataGridView1.Rows.Item(rowNumber).Cells(3).Value = Me.TextBox8.Text
        DataGridView1.Rows.Item(rowNumber).Cells(4).Value = Val(Me.TextBox5.Text) * Val(Me.TextBox8.Text)
        If Me.DataGridView1.Rows.Count > 0 Then
            Me.Label2.Text = FormatNumber(totalsales(), 2).ToString()

        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "check")
    End Try
    TextBox2.Text = ""
    TextBox4.Text = ""
    TextBox5.Text = ""
    TextBox8.Text = ""
    TextBox7.Text = ""
End Sub

1 个答案:

答案 0 :(得分:-1)

致电ExecuteReader后,创建DataTable并调用其Load方法,并传递数据阅读器。然后,您可以将DataTable分配给网格的DataSource属性以显示所有数据,例如

Dim myDataReader = myCommand.ExecuteReader()
Dim myDataTable As New DataTable

myDataTable.Load(myDataReader)
myDataGridView.DataSource = myDataTable