Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I want to know how to concat ListBox values into a string or an array in winforms. Can you guide me or send any code snippets?

Thanks in advance!

[EDIT] : Duplicate question How to concat Listbox values into string in Winforms[^] <-- Duplicate already deleted by Manfred R. Bihy[^]
Posted
Updated 12-Jun-12 3:35am
v6

C#
//Below linq query concat all the selected item
 string required =listBox1.SelectedItems.Cast<string>().Aggregate((a, b)=>a+b);

//Below linq query concat all the distinct selected item
 string required =listBox1.SelectedItems.Cast<string>().Distinct()
                  .Aggregate((a, b)=>a+b);

//Below linq query concat all the selected item with a string in between
 
string required =listBox1.SelectedItems.Cast<string>().Distinct()
                  .Aggregate((a, b)=>a+","+b);
 
Share this answer
 
The solution 1 given by OriginalGriff is good.

Alternatively, using string.Join method and LINQ can be used as follows
C#
//Here object is used as Type argument as the type of items is not given in
//the question. Otherwise, if the type of items in listBox is Person
//then .OfType<Person> can be used

//Array of Items as strings
string[] itemsAsStrings = (from p in listBox1.Items.OfType<object>()
                           select p.ToString()).ToArray();

//Array of Items
object[] arrayOfItems = listBox1.Items.OfType<object>().ToArray();

//Concatenation of all items of list box
string allItems = string.Join(", ",listBox1.Items.OfType<object>());

//Concatenation of selected tiems of list box
string selectedItems= string.Join(", ",listBox1.SelectedItems.OfType<object>());
 
Share this answer
 
v2
Comments
Maciej Los 12-Jun-12 13:14pm    
Nice! +5
VJ Reddy 12-Jun-12 13:22pm    
Thank you, losmac :)
Herman<T>.Instance 10-Jun-15 6:41am    
+5. Linq speeds up over iteration
Best way is to use a StringBulder:
C#
StringBuilder sb = new StringBuilder();
foreach (object o in myListBox.SelectedItems)
    {
    sb.AppendLine(o.ToString());
    }
string s = sb.ToString();
 
Share this answer
 
Comments
VJ Reddy 12-Jun-12 13:11pm    
Good answer. 5!
Maciej Los 12-Jun-12 13:14pm    
Agree with you ;) +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900