根据数据绑定组合框中的选定项目从访问数据库中删除

时间:2012-02-02 12:50:19

标签: .net vb.net winforms ms-access combobox

我有一个数据绑定组合框使用VB2010和MS访问作为数据库..当我点击一个按钮时,组合框中的选定项目将从数据库中删除,不再显示在组合框中......

1 个答案:

答案 0 :(得分:1)

这是一种方法:

使用组合框和按钮创建一个名为ComboDeleteExample的表单。为了创建数据库,我只是将SQL Server AdventureWorks数据库产品表转储到Microsoft Access中。如果您没有SQL Server或Adventure工作,只需创建一个包含两列的Product表; ProductID(int)和Name varchar(25)。

将此代码复制到表单中:

Public Class ComboDeleteExample

    Const _ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Database1.accdb;"
    Private dtProducts As New System.Data.DataTable("Products")

    Private Sub PopulateCombo()
        Using conn As New System.Data.OleDb.OleDbConnection(_ConnectionString)
            conn.Open()
            Dim sqlCmd As New System.Data.OleDb.OleDbCommand("select * from product", conn)
            Dim dr As System.Data.OleDb.OleDbDataReader = sqlCmd.ExecuteReader()
            dtProducts.Load(dr)
        End Using

        ComboBox1.DataBindings.Add(New System.Windows.Forms.Binding("Text", dtProducts, "ProductId", True, DataSourceUpdateMode.OnPropertyChanged))
        ComboBox1.DisplayMember = "Name"
        ComboBox1.DataSource = dtProducts
    End Sub

    Private Sub ComboDeleteExample_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        PopulateCombo()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.SelectedItem IsNot Nothing AndAlso TypeOf (ComboBox1.SelectedItem) Is System.Data.DataRowView Then
            Using conn As New System.Data.OleDb.OleDbConnection(_ConnectionString)
                conn.Open()
                Dim row As System.Data.DataRowView = DirectCast(ComboBox1.SelectedItem, System.Data.DataRowView)
                Dim sqlcmd As New System.Data.OleDb.OleDbCommand(String.Format("delete * from product where productid={0}", row.Item("ProductID")), conn)
                If sqlcmd.ExecuteNonQuery() = 1 Then
                    row.Delete()
                    dtProducts.AcceptChanges()
                End If
            End Using
        End If
    End Sub
End Class