使用comboBox自动完成从自定义类列表中建议

时间:2017-02-25 22:46:26

标签: c# winforms combobox autocomplete

我有一个这样的课程:

public class Region
{
    public string Name { get; set; }
    public string Abbreviation { get; set; }
    public string Area { get; set; }
    public string Picture { get; set; }
    public string DisplayName { get; set; }
}

我有一个comboBox,我在其中设置了这样的项目:

//where regions is a List<Region>
comboBox.DataSource = regions;
comboBox.DisplayMember = "DisplayName";

当用户在comboBox中手动输入文本时,我想建议一些Region.Name.Contains(comboBox.Text)区域。我该如何完成这项工作?

1 个答案:

答案 0 :(得分:0)

不完全是您要查找的内容,但如果您想通过Region.DisplayName.Contains(comboBox.Text)执行,则以下代码可以完成此操作。

public partial class Form1 : Form
{
    List<Region> _regions = new List<Region>();
    public Form1()
    {
        //Some data to test with
        _regions.Add(new Region() { Name = "AA", DisplayName = "11" });
        _regions.Add(new Region() { Name = "AAAA", DisplayName = "111" });
        _regions.Add(new Region() { Name = "AAAAA", DisplayName = "1111" });
        _regions.Add(new Region() { Name = "BBBBBB", DisplayName = "22222" });
        _regions.Add(new Region() { Name = "CCCCC", DisplayName = "333333" });
        InitializeComponent();

        comboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
        comboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
        comboBox.DataSource = _regions;
        comboBox.DisplayMember = "DisplayName";

        var autoCompleteCollection = new AutoCompleteStringCollection();
        if (_regions != null && _regions.Count() > 0)
            foreach (Region region in _regions)
                autoCompleteCollection.Add(region.DisplayName);

        comboBox.AutoCompleteCustomSource = autoCompleteCollection;
    }
}