[英]Add rows in datagridview in vb.net from SQL Server
I am facing a problem here, the below code have no error, but I would like to fetch data from SQL Server and add rows in datagridview rather than show in the textbox and then add to 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
After calling ExecuteReader
, create a DataTable
and call its Load
method, passing your data reader. 调用
ExecuteReader
,创建一个DataTable
并调用其Load
方法,并传递您的数据读取器。 You can then assign that DataTable
to the DataSource
property of grid to display all the data, eg 然后,您可以将该
DataTable
分配给网格的DataSource
属性以显示所有数据,例如
Dim myDataReader = myCommand.ExecuteReader()
Dim myDataTable As New DataTable
myDataTable.Load(myDataReader)
myDataGridView.DataSource = myDataTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.