列表框在asp.net中持久保存多个选定项

时间:2010-07-29 23:57:38

标签: c# asp.net listbox

我将列表框的搜索选择标准保存到另一个名为AreasLb的页面上。可以选择多个区域,我只想设置用户选择的列表框项目.Selected = true

认为以下代码应该可以使用,但它没有,但是没有选择列表框中的项目。

    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;
            }

2 个答案:

答案 0 :(得分:0)

我对你的基于索引的选择略显怀疑 - 不是说这是错的,但我认为可能有更好的方法。我很想使用:

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;                                
        }
    }
}

或者不是迭代ListItems集合,你可以使用Items.FindByText方法来减少foreach并且可能会给你一点性能提升:-):

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;
}

答案 1 :(得分:0)

我想我应该用我找到的最终答案更新这个问题。

我基本上接受别人写的代码,整个节目中都有多个Page.DataBind()。

在母版页中只重新计算了1,这似乎解决了这个问题。

相关问题