How to Populate ComboBox from access db in C#

你说的曾经没有我的故事 提交于 2019-12-25 00:36:32

问题


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. I am only interested in the "Cameras" field. Thank you!


回答1:


You should take a closer look for ADO.NET operations with .mdb files here

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 dAdapter = new OleDbDataAdapter(query, connString);

Now you can use a DataTable object to bind into combobox

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



回答2:


Probably want to add a valuemember to the combobox this way you can link back to the camera id. Try changing the query to:

SELECT CameraID, Cameras From Camers

Then add the cameraID to the value member

combobox.valuemember = "cameraID"

and

combobox.displaymember = "Cameras".



来源:https://stackoverflow.com/questions/2809845/how-to-populate-combobox-from-access-db-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!