如何在VB中从ms访问数据库中显示datagridview中的特定行

时间:2016-10-19 05:34:18

标签: vb.net ms-access datagridview

enter image description here

嗨,我正在开发一个vb项目。我有一个MS访问数据库,有3个coloumns(Itno,Name,Price)。 在表单中,我添加了两个文本框并添加了按钮(TextBox2 = Itno,Textbox = quantity)。 如果用户提供Itno和数量,然后单击添加按钮,则Itno的名称和价格应显示在datagridview中,同时显示在Textbox3中输入的数量。

我已经尝试过我的知识。但我无法在Datagridview中显示数据。任何人都可以帮助我......

导入System.Data.OleDb     Imports System.Data.DataTable

Public Class Form1
    Dim ad As System.Data.OleDb.OleDbDataAdapter
    Dim cm As System.Data.OleDb.OleDbCommand
    Dim co As System.Data.OleDb.OleDbConnection
    Dim dr As System.Data.OleDb.OleDbDataReader
    Dim tb As New DataTable("Table")

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        tb.Columns.Add("Iteam", Type.GetType("System.Int32"))
        tb.Columns.Add("Quantity", Type.GetType("System.String"))
        tb.Columns.Add("Price", Type.GetType("System.String"))
        DataGridView1.DataSource = tb
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        co = New System.Data.OleDb.OleDbConnection
        co.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
                "Data Source=C:\Users\Vicky\Desktop\db\bill\bill.mdb;"
        Try
            co.Open()
            Dim cd As String
            cd = "SELECT * FROM item WHERE Itno='" & TextBox2.Text & "'"
            cm = New OleDb.OleDbCommand(cd, co)
            dr = cm.ExecuteReader()
            While dr.Read()
                Dim n As String
                Dim p As String
                p = dr("Price").ToString
                n = dr("Name").ToString
                tb.Rows.Add(p.ToString, TextBox3.Text, n.ToString)
                DataGridView1.DataSource = tb

            End While
            co.Close()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

        Dim cd As String
        cd = "SELECT * FROM item WHERE Itno=" & TextBox2.Text & ""
        cm = New OleDb.OleDbCommand(cd, co)
        dr = cm.ExecuteReader
        While dr.Read()
            Dim n As String
            Dim p As String
            p = dr("Price").ToString
            n = dr("Name").ToString
            Dim R As DataRow = tb.NewRow
            R("Name") = n.ToString
            R("Quantity") = TextBox3.Text
            R("Price") = p.ToString
            tb.Rows.Add(R)
            DataGridView1.DataSource = tb

我已经更正了代码