Combobox中的数据库访问

时间:2011-12-13 23:06:45

标签: c# winforms

如何在按钮单击时在组合框中插入数据库访问列?它有1列

1 个答案:

答案 0 :(得分:2)

试试这个:

创建一个私有方法,获取ms访问数据并绑定到数据表:

private DataTable BindData()
        {
            using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\YOURDB.mdb; PersSecurity Info=False;")) /your connectionsting
            {
                using (var dAd = new OleDbDataAdapter("select ID,column1 from Table ", conn)) //select query from your DB
                {

                    var dSet = new DataTable();
                    try
                    {
                        conn.Open();

                        dAd.Fill(dSet);

                        return dSet;

                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
        }

然后在按钮上单击添加

        var dt = BindData();
        cmbBox.DataSource = dt;
        cmbBox.DisplayMember = "column1"; //Display Table Column on your DB
        cmbBox.ValueMember = "ID";

另见:

The C# Station ADO.NET Tutorial

此致