9

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?

2
  • 1
    What does the array contain that you've used as datasource? Commented Jun 11, 2015 at 7:42
  • which having both integer and string values . i need answer in c#.net Commented Jun 11, 2015 at 9:00

4 Answers 4

25

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response . As per code clist is List<string> and i can't able to use ListBox.Items.OfType(...) . which indicates reference missing . please specify any solution for this that would be more helpfull.
@user Add using System.Linq
3
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

2 Comments

Thanks for your response. due to performance issue i can't use for loop for this case. can you able to provide solution in foreach loop
there is almost no performance difference between for and foreach, in almost all cases for is faster then foreach
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.