简体   繁体   English

如何从C#中的Access数据库填充ComboBox

[英]How to Populate ComboBox from access db in C#

I have the next combobox: 我有下一个组合框:

this.comboBoxProd.Enabled = false;
this.comboBoxProd.FormattingEnabled = true;
this.comboBoxProd.Items.AddRange(new object[] {
            "Cameras",
            "------------",
            " Digital IXUS 850 IS ",
            " Digital IXUS 900 Ti ",
            " Digital IXUS 75 -NEW- ",
            " Digital IXUS 70 -NEW- ", etc.

I want to change it and take the values from a db. 我想更改它并从数据库中获取值。 My database name is bd1.mdb and in the table Cameras it has the following fields: CamID, Cameras, Warranty, Year. 我的数据库名称为bd1.mdb,在“相机”表中它具有以下字段:CamID,相机,保修,年份。 I am only interested in the "Cameras" field. 我只对“相机”字段感兴趣。 Thank you! 谢谢!

You should take a closer look for ADO.NET operations with .mdb files here 您应该在这里仔细查看ADO.NET与.mdb文件的操作

First,prepare your connection string 首先,准备您的连接字符串

string connString = "Microsoft.Jet.OLEDB.4.0;Data Source=C:\\bd1.mdb";

Next step is to prepare your query 下一步是准备您的查询

string query = "SELECT Cameras FROM Cameras";

You will need an adapter to bind datasource,in your case it's OleDbDataAdapter 您将需要一个适配器来绑定数据源,在这种情况下,它是OleDbDataAdapter

OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);

Now you can use a DataTable object to bind into combobox 现在,您可以使用DataTable对象绑定到组合框

DataTable source = new DataTable();

Fill data into your source 将数据填充到您的源中

dAdapter.Fill(source);

Your source is full with Cameras,now you can refer to your combobox control 您的资料来源中包含相机,现在可以参考组合框控件

combobox.DataSource = source;

DO NOT FORGET THAT you should that which field will be displayed in Combobox items 不要忘记您应该在组合框项目中显示哪个字段

combobox.DataTextField = "Cameras";//from query

Probably want to add a valuemember to the combobox this way you can link back to the camera id. 可能想以这种方式将valuemember添加到组合框,以便可以链接回相机ID。 Try changing the query to: 尝试将查询更改为:

SELECT CameraID, Cameras From Camers

Then add the cameraID to the value member 然后将cameraID添加到value成员

combobox.valuemember = "cameraID"

and

combobox.displaymember = "Cameras" . combobox.displaymember = "Cameras"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM