简体   繁体   English

Winform C#组合框变量选项

[英]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. 因此,如果我将1插入May表测试中。 my combobox will have an option 1. 我的组合框将有一个选项1。

I wonder how to do it :| 我不知道该怎么做:|

Using query and DataSource . 使用查询和DataSource Just get your data from the DB and bind it to the Combobox . 只需从数据库中获取数据并将其绑定到Combobox You can do it via DataSource property. 您可以通过DataSource属性来实现。

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. 我喜欢使用foreach。 Load the database record string into the array or directly into the foreach below. 将数据库记录字符串加载到数组中或直接加载到下面的foreach中。

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. 我认为DataBinding是最好的选择。
Use the following properties for the ComboBox: 将以下属性用于ComboBox:
1. DataSource -> Table 1. 数据源 ->表
2. DisplayMember and 2. DisplayMember
3. ValueMember 3. ValueMember

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

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