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
_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.