How List <string> becomes AutoCompleteStringCollection
I have a list, I want to convert it to autoCompleteStringCollection .. And I do not want to use foreach.
_textbox.AutoCompleteMode = AutoCompleteMode.Append; _textbox.AutoCompleteSource = AutoCompleteSource.CustomSource; _textbox.AutoCompleteCustomSource = user.GetNameUsers() as AutoCompleteStringCollection; Note: user.GetNameUsers () is a list.
The code does not work, it becomes zero.
thanks
+4
2 answers
_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; } } Using:
_textbox.AutoCompleteCustomSource = user.GetUsers().ToAutoCompleteStringCollection(); +14
By checking the documentation for AutoCompleteStringCollection , and in particular the constructor, I see that there is no constructor that accepts a List .
Therefore, you have 2 options.
1) Use AddRange to add all list items to a new instance of AutoCompleteStringCollection
var acsc= new AutoCompleteStringCollection(); acsc.AddRange(user.GetNameUsers().ToArray()); 2) Inherit a new class that adds the constructor you need, and call the same code as above.
public class MyAutoCompleteStringCollection : AutoCompleteStringCollection { public MyAutoCompleteStringCollection(IEnumerable items) { this.AddRange(items.ToArray()) } } So you can use
_textbox.AutoCompleteCustomSource = new MyAutoCompleteStringCollection (user.GetNameUsers()); Personally, I would go with option 1 at the moment.
+1