Spencer
Spencer

Reputation: 642

c# copy selected listbox items into a string

I'm having some issues with getting selected values from a listbox into a string.

The list box contains multiple values, let's call them A-Z. Basically, I want to copy the selected items into a string.

var listarray = new System.Collections.ArrayList(listboxName.SelectedItems);

string myval = "";

foreach (var arr in listarray)
{
    myval = dep.ToString();
    Console.WriteLine(myval); // this shows all the selected values
}

string finalStr = "some text before the values" + myval;
Console.WriteLine(finalStr);

I want the string to display "some text before the values A, B, C, D...", but instead, it outputs "some text before the values A"

The last Console.WriteLine only shows one value as opposed to all the selected values. I've tried adding the finalStr inside the foreach loop, but this creates multiple instances of the finalStr instead of just one string with multiple array values.

Upvotes: 2

Views: 4551

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Use String.Join to build concatenated string from items collection:

string finalStr = "Some text before the values " + 
           String.Join(", ", listboxName.SelectedItems.Cast<YourItemType>());

Upvotes: 5

empi
empi

Reputation: 15881

You're always setting myval to current value of dep.ToString - you should concatenate it (I think you meant arr not dep):

myval += arr.ToString() + ", ";

The easiest way to deal with the commas is to create additional list and use String.Join:

var selected = new List<string>();
foreach (var arr in listboxName.SelectedItems)
{
    selected.Add(arr.ToString());    
}

string finalStr = "some text before the values" + String.Join(", ", selected);

Upvotes: 0

Related Questions