combo box and Generic list
I'm Having a list
List<string> strArraylist = new List<string>();
i want to add to it the values of a combo bo开发者_StackOverflow中文版x ..
UPDATE: I just realize you may have been asking the opposite of what I provided below: how to added the items from a ComboBox
to a List<string>
. If that's the case, you could always do it like this:
List<string> strList = new List<string>();
strList.AddRange(cbx.Items.Cast<object>().Select(x => x.ToString()));
Here's an extension method I use:
public static class ControlHelper
{
public static void Populate<T>(this ComboBox comboBox, IEnumerable<T> items)
{
try
{
comboBox.BeginUpdate();
foreach (T item in items)
{
comboBox.Items.Add(item);
}
}
finally
{
comboBox.EndUpdate();
}
}
}
This allows you to populate a ComboBox
with any generic collection that can be enumerated. See how easy it is to call:
List<string> strList = new List<string> { "abc", "def", "ghi" };
cbx.Populate(strList);
Notice that you could also make this method non-generic, since the ComboBox.Items
property is of a non-generic type (you can add any object
to Items
). In this case the Populate
method would accept a plain IEnumerable
instead of an IEnumerable<T>
.
精彩评论