views:

55

answers:

1

I am persisting the search selection criteria of a listbox onto another page which is called AreasLb. Multiple areas can be selected, I simply want to set the listbox items that the user selected as .Selected = true

I think the below code should work, but it doesn't, with no items in the Listbox being selected.

    if (s == "Areas")
            {
                string[] area = nv[s].Substring(0, (nv[s].Length - 1)).Split(';');

                int i = 0;
                foreach (ListItem item in AreasLb.Items)
                {
                    foreach (var s1 in area)
                    {
                        if (s1 == item.Value)
                        {
                            AreasLb.Items[i].Selected = true;                                
                        }
                        continue;
                    }

                    i = i + 1;
                }

                continue;
            }
A: 

I'm slightly suspicious of your index-based selection - not saying it's wrong but I think there may be better ways. I'd be tempted to use:

string[] area = nv[s].Substring(0, (nv[s].Length - 1)).Split(';');

foreach (ListItem item in AreasLb.Items)
{
    foreach (var s1 in area)
    {
        if (s1 == item.Value)
        {
            item.Selected = true;                                
        }
    }
}

Or rather than iterating through the set of ListItems, you could use the Items.FindByText method which cuts out a foreach and may give you a bit of a performance increase :-) :

ListItem foundItem = null;

string[] area = nv[s].Substring(0, (nv[s].Length - 1)).Split(';');

foreach (var s1 in area)
{
    // Search for a ListItem with the text from the array
    foundItem = AreasLb.Items.FindByText(s1);

    if (foundItem == null)
    {
        // We didn't find a matching item
    }
    else
    {
        // We found a matching item so select it
        foundItem.Selected = true;
    }

    foundItem = null;
}
PhilPursglove
thank i like the second solution.. but as far as the question i think every version shown should work but none do. something else is definitely happening to cause it not to work. no idea what though
N00b
@N00b Where does your code appear in the Page lifecycle? Can you post a bit more of your surrounding code?
PhilPursglove
There is a method call to the code above in the PageLoad after the check on whether we are posting back or not. The method does not get hit on postback.
N00b