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[] are开发者_开发知识库a = 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;
}
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;
}
Thought I should update this question with the eventual answer that I found.
I was basically taking on code someone else wrote and there was multiple Page.DataBind() all over the show.
Re-factored so only 1 in the masterpage and that seemed to have resolved the issue.
精彩评论