0

我正在尝试通过代码连接到访问数据库。我将最后一点大写,因为我很清楚这样做的视觉方法,但在这种情况下不能使用该方法。基本上,我只想从显示列 Year 的表 Title 中的单个列上创建一个组合框的数据绑定。为了澄清这一点,我想用 YearPublished 列中的数据填充 cboYearsFillBy。我发现最大的痛苦是,当找不到 db 时,vb 不会大惊小怪,所以我什至不知道它是否找到了它。我的代码如下

  Imports System.Data.OleDb

    Public Class frmTitle
    ' Create untyped dataTables
    Dim dtYears As New DataTable

    ' Declare a variable to represent the DataAdapter
    Dim daYears As OleDbDataAdapter
    ' Create BindingSource objects for Employee & Dept tables:
    Dim WithEvents bsYears As New BindingSource

    Private Sub frmTitle_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim connStr As String = "Provider=Microsoft.ace.OLEDB.12.0;Data Source=D:\VisualStudioProjects\Biblio.accdb"
        MessageBox.Show(connStr)
        Dim titleSQLStr As String = "SELECT * FROM Title"
        daYears = New OleDbDataAdapter(titleSQLStr, connStr)
        Dim commandBuilder As New OleDb.OleDbCommandBuilder(daYears)
        daYears.Fill(dtYears)
        dtYears.PrimaryKey = New DataColumn() {dtYears.Columns("YearPublished")}
        bsYears.DataSource = dtYears
        cboYearsFillBy.DataSource = bsYears
        cboYearsFillBy.DisplayMember = "YearPublished"
        cboYearsFillBy.ValueMember = "YearPublished"

    End Sub
    End Class

我得到以下输出 输出

4

1 回答 1

0
Imports System.Data.OleDb

Public Class frmTitle
' Create untyped dataTables
Dim dtYears As New DataTable

' Declare a variable to represent the DataAdapter
Dim daYears As OleDbDataAdapter
' Create BindingSource objects for Employee & Dept tables:
Dim WithEvents bsYears As New BindingSource

Private Sub frmTitle_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim connStr As String = "Provider=Microsoft.ace.OLEDB.12.0;Data Source=D:\VisualStudioProjects\Biblio.accdb; Persist Security Info=True"
    MessageBox.Show(connStr)
    Dim con As New OleDbConnection
    con = New OleDbConnection(connStr)
    If con.State = ConnectionState.Closed Then
    con.Open()
    End If
    Dim titleSQLStr As String = "SELECT * FROM Title"
    daYears = New OleDbDataAdapter(titleSQLStr, connStr)
    daYears.Fill(dtYears)
    cboYearsFillBy.DataSource = dtYears
    cboYearsFillBy.DisplayMember = "YearPublished"
    cboYearsFillBy.ValueMember = "YearPublished"
    con.Close()  
End Sub

End Class

我简化了你的代码,现在试试

于 2013-11-12T03:12:56.140 回答