2010-07-29 105 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

相關問題