简体   繁体   中英

Winform C# Combobox variable options

How could I make the options of my combobox a variable.

I want its values to depend on a certain field in my database.

for ex. If I have a table test and it has a field number.

Everytime I insert a value on my field it will be included in the options in my combobox.

so if i insert 1 into may table test. my combobox will have an option 1.

I wonder how to do it :|

Using query and DataSource . Just get your data from the DB and bind it to the Combobox . You can do it via DataSource property.

List<string> myComboboxVaues = new List<string>()
{
    "Value 1",
    "Value 2",
    "Value 3"
};

this.comboBox1.DataSource = myComboboxVaues;

Instead of list of strings use retrieved from DB data.

I like using foreach. Load the database record string into the array or directly into the foreach below.

string[] arr = new string[4]; // Initialize
arr[0] = "one";               // Element 1
arr[1] = "two";               // Element 2
arr[2] = "three";             // Element 3
arr[3] = "four";              // Element 4


foreach (string x in arr)
{
    comboBox1.Items.Add(x);
}

I think DataBinding is the best option.
Use the following properties for the ComboBox:
1. DataSource -> Table
2. DisplayMember and
3. ValueMember

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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