我正在尝试通过在文本框中键入来搜索项目代码,并且我想从 SQL 数据库中获取同一行中的特定列。我在 datagridview 中创建了带有标题的列,我希望在特定的 datagridview 列中搜索数据。我已经编写了代码,但它不起作用。我不知道该怎么做。我是新手,正在尝试学习 vb。请给一些建议。
这是我的代码:
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
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
我使用位于 DataGridView 外部的 TextBox 来输入要搜索的项目代码。我添加了一个按钮来进行搜索并将数据检索到 DataReader。
DataReader 然后加载声明为表单级别(类级别变量)的 DataTable。我们希望每次搜索时都使用相同的 DataTable,以便将项目添加到网格中。如果 DataTable 已经包含行,则使用 Load 方法,来自数据源的传入数据将与现有行合并。然后将 DataTable 绑定到 DataGridView。每次用户在 TextBox 中输入项目代码并单击搜索按钮时,都会向网格中添加一个新行。
为了使列标题看起来更漂亮,请在 Select 语句中用作别名。数据库列名称后面的 As 子句是别名,将作为标题显示在 DataGridView 中。如果别名中有空格,则必须将其括在单引号中。
Private dt As DataTable
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt = New DataTable()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
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", txtItemCode.Text)
cn.Open()
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub
PS 很高兴看到使用参数和使用块!:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句