简体   繁体   English

将字符串列表绑定到ComboBox

[英]Binding String List to ComboBox

I am binding a List<String> to a ComboBox. 我将List<String>绑定到ComboBox。 I wrote this in two ways. 我用两种方式写这本书。 The first way, the output of ComboBox was empty. 第一种方法,ComboBox的输出为空。 Where i was wrong? 我哪里错了? please help me. 请帮我。 this is my code: 这是我的代码:

public class MaritalStatusComboBox:ComboBox
{
   public MaritalStatusComboBox()
    {       
        BindingSource bs = new BindingSource();
        bs.DataSource = new List<string> {"Single","Married" };

    }
}

and The Second way : 和第二种方式:

public class MaritalStatusComboBox:ComboBox
{
    List<string> list = new List<string>() { "Single", "Married" };
    public MaritalStatusComboBox()
    {
        this.Items.Clear();
        foreach (string str in list)
        {
            this.Items.Add(str);
        }

    }
}

output of ComboBox include of it: Single, Married, Collection Why does Collection appear in my ComboBox? ComboBox的输出包括:Single,Married, Collection为什么Collection出现在我的ComboBox中?

In this first method, you didn't connect the DataSource: 在第一种方法中,您没有连接数据源:

BindingSource bs = new BindingSource();
bs.DataSource = new List<string> { "Single", "Married" };
this.DataSource = bs;

The second method worked. 第二种方法有效。 The posted code does not show the word "Collection". 所发布的代码未显示单词“ Collection”。

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

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