2010-07-29 102 views
0

我将列表框的搜索选择标准保存到另一个称为AreasLb的页面上。多个区域可以选择,我只是想设置的用户选择.Selected =真列表框在asp.net中保留多个选定的项目

认为下面的代码应该工作列表框项目,但事实并非如此,在列表框是没有任何项目选择。

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

你知道你是否在触及'AreasLb.Items [i] .Selected = true;'行吗?一旦你完成了这段代码,你可以检查'AreasLb.Items'并查看数组中的正确项是否设置为true? – 2010-07-30 00:44:26

+0

我打这条线,是的,它被选中并设置为true。我在负载中有一个!Page.IsPostback,所以没有错误。 – asn1981 2010-07-30 01:11:45

回答

0

想我应该更新这个问题与我发现的最终答案。

我基本上正在接受别人写的代码,并且在整个演出中都有多个Page.DataBind()。

在主页中重新考虑了因此只有1,并且似乎解决了问题。

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

感谢我喜欢第二个解决方案..但是,至于我认为所显示的每个版本都应该可以工作但没有问题的问题。肯定会发生其他事情,导致它不起作用。不知道什么 – asn1981 2010-07-30 12:37:35

+0

@ N00b你的代码在页面生命周期中出现在哪里?你可以多发一些你周围的代码吗? – PhilPursglove 2010-07-30 13:26:11

+0

在检查我们是否回发或没有回复之后,在PageLoad中有一个方法调用上面的代码。该方法不会在回发中受到影响。 – asn1981 2010-08-02 08:49:06

相关问题