Abhilash Srivastava
Abhilash Srivastava

Reputation: 85

ASP.NET how to select checkbox list items with comma separated string

I have a checkedlistBox cblHobbies

StringBuilder hobbies = new StringBuilder(string.Empty);
foreach (ListItem li in cblHobbies.Items) {
    if (li.Selected) {
        hobbies.Append(li).Append(", ");
    }
}
string hobby = hobbies.ToString().TrimEnd(' ').TrimEnd(',');

I am storing hobby in SQL Server database as Varchar(MAX).

When the user edit his profile i want all the hobbies get selected already.

My Question is how to select checklistbox items from a comma separated list efficiently? (in respect of number of iterations)

Upvotes: 0

Views: 6629

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Summarizing my comments:

  • You can use following readable one-liner instead of your StringBuilder-loop:

    string hobby = String.Join(", ", cblHobbies.Items.Cast<ListItem>()
                                               .Where(i=> i.Selected));
    
  • Never store multiple informations in one value in your database. Instead store every selected item in it's own record. So this comma separated string does not belong there. Normalize your Database.

    • That's much more efficient
    • allows easier queries
    • avoids corrupt data
    • etc. ...

However, aren't you mirco optimizing things? If you have read the value from database you can use a simple loop to select them. It's very efficient.

string hobby = GetHobbyFromDB();
string[] hobbies = hobby.Split(new []{", "}, StringSplitOptions.None);

foreach (ListItem li in cblHobbies.Items)
    li.Selected = hobbies.Contains(li.Text);

Upvotes: 3

Related Questions