Splitting combined string for checklistbox control

919 Views Asked by At

RE: Customised Web Application for Microsoft CRM Online

I've programmed a checklistbox control in ASP.NET (C#) Web Form that displays a number of items from Microsoft CRM Online via LINQ.

List<string> selDropdown = chkMyItemsHere.Items.Cast<ListItem>()
                .Where(li => li.Selected)
                .Select(li => li.Value)
                .ToList();

string ListBoxValues = string.Join(", ", selDropdown);

This works perfectly and I'm able to save the string into one field (i.e. 'string value, string value').

Now, on Page_Load I need to split the values from the combined string and tick the relevant checkboxes in the checkListbox.

string[] k = i.LINQFIELD.Split(',');
for (int m = 0; m <= k.Length - 1; m++)
{
    for (int x = 0; x <= chkMyItemsHere.Items.Count; x++)
    {
       if (chkMyItemsHere.Items[x].Value == k[m])
       {
          chkMyItemsHere.Items[x].Selected = true;
       }
     }
}

Any ideas why this wouldn't be re-populating my checkboxlist? Any help would be greatly appreciated.

2

There are 2 best solutions below

5
On

In your code that works, you have this:

string.Join(", ", selDropdown);

In your code that does not, you have this:

string[] k = i.LINQFIELD.Split(',');

Do you see it?

As a solution, I propose you declare a constant variable like so:

private const string SPLIT_VARIABLE = ", ";

Now you have this:

string.Join(SPLIT_VARIABLE, selDropdown);

and

string[] k = i.LINQFIELD.Split(SPLIT_VARIABLE);
0
On

After fixing how you split your comma-delimited string -- as suggested by jp2code to make sure there aren't extraneous spaces in each array element -- you can also use LINQ to select the items in your checkboxlist based on what's in your "k" string array:

(from i in chkMyItemsHere.Items.Cast<ListItem>()
             where Array.Exists<string>(k, s => { return i.Value == s; })
             select i).ToList().ForEach(i => i.Selected = true);

This way, you don't have to use a nested for loop to select your list items.