How to set mySQL data source for combo box (C#)

断了今生、忘了曾经 提交于 2019-12-13 07:12:47

问题


I am a beginner at C# and am having some serious issues setting the data source of a combo box. What I want to have happen is as follows: I want the combo box on my C# windows forum to be populated with the string names in just one column of a table in my mySQL database.

The mySQL table has the following format:

river_id, river_name, ....... (other columns) 
_____________________________________________
1           river1
2           river2         
3           river3
4           river4
5           river5
6           river6

What I want to happen is have the combo box be populated with each river name. Here is my attempt:

 string query = "SELECT * FROM sources";
       MySqlDataAdapter riverSourcesAdapter = new MySqlDataAdapter(query,connectionString);
       DataSet riverDataSet = new DataSet();
       riverSourcesAdapter.Fill(riverDataSet);

       comboBox1.Text = riverDataSet.Tables[0].Rows[0][0].ToString();

I also tried setting the combo box datasource and datamember in the designer instead, but that approach did not seem to work either.


回答1:


Try this:

comboBox1.DataSource = riverDataSet.Tables[0];
comboBox1.DisplayMember = "<column name>";
comboBox1.ValueMember = "<column name>";



回答2:


your code should be like this..

comboBox1.DataSource = riverDataSet;
comboBox1.DisplayMember = "river_name";
comboBox1.ValueMember = "river_id";
comboBox1.SelectedIndex = -1;
comboBox1.AutoCompleteMode = AutoCompleteMode.Append;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;


来源:https://stackoverflow.com/questions/24459216/how-to-set-mysql-data-source-for-combo-box-c

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