Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Private Sub loadData()
If Not cnn.State = ConnectionState.Open Then
cnn.ConnectionString = "Provider=Microsoft.ACE.Oledb.12.0; Data Source=" & Application.StartupPath & "\LibrarySystem.accdb"
'open connection
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT StatusID, StatusDesc FROM BookStatus", cnn)
Dim dt As New DataTable
'fill data to datatable
da.Fill(dt)
'show data in data table into combobox
Me.cmbBookStatus.DataSource = dt
Me.cmbBookStatus.DisplayMember = "StatusDesc"
Me.cmbBookStatus.ValueMember = "StatusID"
'close connection
cnn.Close()
End Sub
我想在datagridview上显示组合框中的数据。以上是我使用的代码。我在bookstatus的microsoft访问中创建了一个表。但数据仍然没有显示在组合框中。有人可以帮助我吗?
我将用于在datagridview上查看组合框数据的代码放在保存按钮下。
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.ConnectionString = "Provider=Microsoft.ACE.Oledb.12.0; Data Source=" & Application.StartupPath & "\LibrarySystem.accdb"
cnn.Open()
End If
If (txtBookID.Text = "" And txtBookTitle.Text = "" And txtPub.Text = "" And txtAuthor.Text = "" And cmbBookStatus.SelectedValue = "") Then
MessageBox.Show("Please insert all field!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim msgbox As DialogResult = MessageBox.Show("Are you sure to save this record?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If msgbox = Windows.Forms.DialogResult.Yes Then
'add new data
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Book(BookID, Title, Publisher, Author, StatusID) " & _
" VALUES('" & txtBookID.Text & "','" & txtBookTitle.Text & "','" & txtPub.Text & "','" & txtAuthor.Text & "','" & cmbBookStatus.SelectedValue & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("Data has been recorded", "Add New Record", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtBookID.Clear()
txtBookTitle.Clear()
txtPub.Clear()
txtAuthor.Clear()
End If
'refresh data
'Me.loadData()
Dim db As New OleDb.OleDbDataAdapter("SELECT * FROM Book", cnn)
Dim dt As New DataTable
'fill data to datatable
db.Fill(dt)
'show data in data table into datagridview
Me.dgvAddBook.DataSource = dt
Dim column As DataGridViewColumn = dgvAddBook.Columns(1)
column.Width = 269
End If
'close connection
cnn.Close()
End Sub