user3631120
user3631120

Reputation: 109

How to convert ListBox.items to string of array collection in c#

I have bound array as datasource for ListBox . Now i need to convert listbox.Items to string of array collection.

foreach (string s1 in listBoxPart.Items)
{
   clist.Add(s1);
}

here clist is string list, so how can i add ListBox.items to clist?

Upvotes: 9

Views: 30889

Answers (4)

Barend van der Walt
Barend van der Walt

Reputation: 373

Just create a list of strings and then add the item.toString() to it.

var list = new List<string>();

foreach (var item in Listbox1.Items)
{
    list.Add(item.ToString());
}

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460028

If the array which is the datasource contains strings:

clist.AddRange(listBoxPart.Items.Cast<string>());

or if the DataSource is a String[] or List<string>:

clist.AddRange((Ilist<string>)listBoxPart.DataSource);

if this is actually ASP.NET:

clist.AddRange(listBoxPart.Items.Cast<ListItem>().Select(li => li.Text));

Upvotes: 0

Vajura
Vajura

Reputation: 1132

for (int a = 0; a < listBoxPart.Items.Count; a++)
    clist.Add(listBoxPart.Items[a].ToString());

This should work if the items saved in the list are actualy strings, if they are objects you need to cast them and then use whatever you need to get strings out of them

Upvotes: 3

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

You can project any string contained inside Items using OfType. This means that any element inside the ObjectCollection which is actually a string, would be selected:

string[] clist = listBoxPart.Items.OfType<string>().ToArray();

Upvotes: 24

Related Questions