Skip to main content

Populate selected items of CheckBoxList/ListBox from comma separated string in C#

In my last post I have described how you can get a comma separated string of selected value of a CheckBoxList or Listbox.
In this example I am writing a method which will take string of values (comma separated) and CheckBoxList/ListBox as parameter and populate provided control.

In few examples I have found that user have iterated over two loops to populate selected items, but here I am iterating over only Control’s item and then make use of LINQ over splitted string instead of iterating over it. So here comes power of LINQ over normal iterating code and this is more efficient way of doing this as we needn’t to run loop inside another loop and just one line of LINQ code served our purpose.

Note: Please include System.Text and System.Web.UI.WebControls and System.Linq namespaces for this sample code.

So here we go:
//for Listbox:pass ListBox control.
private void PopulateSelectedItems(string selectedItems, CheckBoxList control)
{
    if (!string.IsNullOrWhiteSpace(selectedItems))
    {
        string[] items = selectedItems.Split(',');
        foreach (ListItem item in control.Items)
        {
            item.Selected = items.Where(c => c.Equals(item.Value))
                            .FirstOrDefault() != null;
        }
    }
}


Use this function as:              
PopulateSelectedItems(selectedItems, control); //control is name of Checkboxlist/ListBox

Comments