how List<string> become AutoCompleteStringCollection

流过昼夜 提交于 2019-12-06 02:25:57

问题


I have list, i want to convert it to autoCompleteStringCollection.. And I don't want use foreach.

        _textbox.AutoCompleteMode = AutoCompleteMode.Append;
        _textbox.AutoCompleteSource = AutoCompleteSource.CustomSource;
        _textbox.AutoCompleteCustomSource = user.GetNameUsers() as AutoCompleteStringCollection;

Note user.GetNameUsers() is list.

Code doesn't work, it become null.

Thank you


回答1:


_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();



回答2:


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.



来源:https://stackoverflow.com/questions/4678194/how-liststring-become-autocompletestringcollection

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