将数据从Microsoft Access绑定到文本框

时间:2013-12-13 08:51:25

标签: vb.net combobox textbox ms-access-2007

我有一个名为PriceTesting的数据库(使用Microsoft Access 2007),其中包含一个名为tbl_dress的表,其中包含以下列:

Dress_ID, Dress_Name, Dress_Price

在表单中,我创建了一个组合框和一个文本框。

到目前为止,我已成功使用此代码将组合框与Dress_Name数据绑定: -

Private Sub FillCombo()
        Try
            Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
            Dim query As String = ("SELECT Dress_Name FROM tbl_dress")
            Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
            Dim ds As New DataSet
            da.Fill(ds)
            ComboBox1.ValueMember = "Dress_Name"
            ComboBox1.DataSource = ds.Tables(0)
            ComboBox1.SelectedIndex = 0
        Catch ex As Exception
            MsgBox("ERROR : " & ex.Message.ToString)
        End Try
    End Sub

并且它有效...每次加载表单时,组合框都包含Dress_Name列的数据。

现在我想要texbox.text = Dress_Price WHERE Dress_Name = combox.selecteditem

任何想法怎么做? 我的想法只有这个: -

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged

query = " SELECT Dress_Price FROM tbl_dress WHERE Dress_Name = ' " & Combobox1.Text & " ' "
Textbox1.text = query

End Sub

2 个答案:

答案 0 :(得分:0)

Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
Dim query As String = " SELECT Dress_Price FROM tbl_dress WHERE Dress_Name = ' " & Combobox1.Text & "'" 
Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
Dim dt As New DataTable
da.Fill(dt)
Textbox1.text = dt.rows(0).item(0)

搜索参数以避免sql注入。还尝试改进查询并使用ID而不是dress_name

答案 1 :(得分:0)

尝试并确保在查询中添加 Dress_Price

Private Sub FillCombo()
    Try
        Dim fillcon As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\DressTest\DressTest\db\PriceTesting.accdb")
        Dim query As String = ("SELECT Dress_Name, Dress_Price FROM tbl_dress")
        Dim da As New OleDb.OleDbDataAdapter(query, fillcon)
        Dim ds As New DataSet
        da.Fill(ds)
        ComboBox1.ValueMember = "Dress_Name"
        ComboBox1.DataSource = ds.Tables(0)
        ComboBox1.SelectedIndex = 0

        texbox.DataBindings.Clear()
        texbox.DataBindings.Add("Text", ds.Tables(0), "Dress_Price")

    Catch ex As Exception
        MsgBox("ERROR : " & ex.Message.ToString)
    End Try
End Sub

或者只是更改您想法中的代码,并确保在查询中添加 Dress_Price

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    dim dt as DataTable = Combobox1.DataSource
    dim dr as DataRow = dt.Rows(Combobox1.SelectedIndex)
    Textbox1.text = iif(dr.isNull("Dress_Price"), "", dr.isNull("Dress_Price").Tostring)
End Sub