Skullomania
Skullomania

Reputation: 2215

How do I modify selected items in asp:listbox for use in a proper string?

Lets say I wanted to create an application for a user to select trouble departments for reporting purposes. The user would go in and select multiple trouble departments from a asp:ListBox and when the user hits send the email would read,

We are having trouble in the following departments: DepartmentA, DepartmentB.

What I have been able to is figure out how to properly loop the items out from the loop, however the last item has a , at the end of the last item. For example instead of reading the proper way as noted above it looks like this:

We are having trouble in the following departments: DepartmentA, DepartmentB,.

Here is my code:

string DeptID = string.Empty;
foreach (ListItem li in lstDSXDepartment.Items)
{
    if (li.Selected == true)
    {
        DeptID += li.Value + ",";
    }
}

Response.Write("We are having trouble with the following Departments: " + DeptID + ".");

How do I fix the string so that the comma does not show at the end of list of selections?

Upvotes: 0

Views: 56

Answers (2)

Win
Win

Reputation: 62290

You can use string.join. It is much easier.

var ids = lstDSXDepartment.Items
    .Cast<ListItem>()
    .Where(x=> x.Selected)
    .Select(x=> x.Value);
string text = string.Join(",", ids);

Other thought:

If you want to use your original method, you should consider using StringBuilder instead of String because String is immutable.

StringBuilder will significantly improve the performance depending on the number of Items.

Upvotes: 3

Andrew_CS
Andrew_CS

Reputation: 2562

Just use a trim function to remove the unwanted comma.

DeptID = DeptID.TrimEnd(',');

Use after the loop, before writing.

Note: The TrimEnd function returns a new copy that is modified of the original string so you have to store it back into your original variable. This is because strings are immutable in C#.

Upvotes: 1

Related Questions