2009-07-01 59 views

回答

6

這是VB代碼,這樣做......

myListBox.SelectionMode = Multiple 
For each i as listBoxItem in myListBox.Items 
    if i.Value = WantedValue Then 
     i.Selected = true 
    end if 
Next 
12

這裏是一個C#示例


(CSS)

<form id="form1" runat="server"> 
     <asp:ListBox ID="ListBox1" runat="server" > 
      <asp:ListItem Value="Red" /> 
      <asp:ListItem Value="Blue" /> 
      <asp:ListItem Value="Green" /> 
     </asp:ListBox> 
     <asp:Button ID="Button1" 
        runat="server" 
        onclick="Button1_Click" 
        Text="Select Blue and Green" /> 
</form> 

(代碼隱藏)

protected void Button1_Click(object sender, EventArgs e) 
{ 
    ListBox1.SelectionMode = ListSelectionMode.Multiple;    
    foreach (ListItem item in ListBox1.Items) 
    { 
      if (item.Value == "Blue" || item.Value == "Green") 
      { 
       item.Selected = true; 
      } 
    } 
} 
11

你將不得不使用列表框

foreach (string selectedValue in SelectedValuesArray) 
        { 
         lstBranch.Items.FindByValue(selectedValue).Selected = true; 
        } 
+1

+1這在我看來是最好的選擇,因爲它只能通過需要的物品,而不是整個列表框集合迭代。我用我自己的解決方案,謝謝Phu! – 2014-02-20 23:35:18

0

我喜歡在那裏bill berlington與他解去的FindByValue方法。我不想迭代我的數組中的每個項目的ListBox.Items。這裏是我的解決方案:

foreach (int index in indicesIntArray) 
{ 
    applicationListBox.Items[index].Selected = true; 
} 
1

在C#:

foreach (ListItem item in ListBox1.Items) 
{ 
    item.Attributes.Add("selected", "selected"); 
} 
相關問題