how List<string> become AutoCompleteStringCollection

时光总嘲笑我的痴心妄想 提交于 2019-12-04 07:42:36
_textbox.AutoCompleteMode = AutoCompleteMode.Append;
_textbox.AutoCompleteSource = AutoCompleteSource.CustomSource;
var autoComplete = new AutoCompleteStringCollection();
autoComplete.AddRange(user.GetNameUsers().ToArray());
_textbox.AutoCompleteCustomSource = autoComplete;

If you need this often, you can write an extension method:

public static class EnumerableExtensionsEx
{
    public static AutoCompleteStringCollection ToAutoCompleteStringCollection(
        this IEnumerable<string> enumerable)
    {
        if(enumerable == null) throw new ArgumentNullException("enumerable");
        var autoComplete = new AutoCompleteStringCollection();
        foreach(var item in enumerable) autoComplete.Add(item);
        return autoComplete;
    }
}

Usage:

_textbox.AutoCompleteCustomSource = user.GetUsers().ToAutoCompleteStringCollection();

Having checked the documentation for AutoCompleteStringCollection, and specifically the constructor I see there is no constructor which takes a List.

Therefore, you have 2 options.

1) Use AddRange to add all your list items to a new instance of AutoCompleteStringCollection

var acsc= new AutoCompleteStringCollection();
acsc.AddRange(user.GetNameUsers().ToArray());

2) Inherit a new class, which adds the constructor you need, and call much the same code as above internally.

public class MyAutoCompleteStringCollection : AutoCompleteStringCollection
{
  public MyAutoCompleteStringCollection(IEnumerable items)
  {
     this.AddRange(items.ToArray())
  }
}

Thus you can use

_textbox.AutoCompleteCustomSource = new MyAutoCompleteStringCollection (user.GetNameUsers());

Personally, i'd go with option 1 for now.

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