【问题标题】:Listbox persisting multiple selected items in asp.net列表框在asp.net中保留多个选定项目
【发布时间】:2010-07-29 23:57:38
【问题描述】:

我将列表框的搜索选择标准保存到另一个称为 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;
            }

【问题讨论】:

  • 你知道你是否打到AreasLb.Items[i].Selected = true; 行吗?完成这部分代码后,您能否检查AreasLb.Items 并查看数组中的正确项是否设置为true?
  • 我正在打那条线,是的,它被选中并设置为 true。我确实有一个 !Page.IsPostback 加载,所以那里没有出错。

标签: c# asp.net listbox


【解决方案1】:

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

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

或者,您可以使用 Items.FindByText 方法,而不是遍历 ListItems 集,该方法会删除 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;
}

【讨论】:

  • 谢谢我喜欢第二种解决方案.. 但就问题而言,我认为显示的每个版本都应该有效,但没有一个有效。肯定会发生其他事情导致它不起作用。不知道是什么
  • @N00b 您的代码出现在页面生命周期的什么位置?你能发布更多你周围的代码吗?
  • 在检查我们是否回发后,PageLoad 中有对上述代码的方法调用。该方法在回发时不会被命中。
【解决方案2】:

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

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

重新分解,因此母版页中只有 1 个,这似乎解决了问题。

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多