2009-07-01 65 views

Trả lời

6

đây là đoạn code VB để làm như vậy ...

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

Dưới đây là một C# mẫu


(aspx)

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

(Mã Đằng sau)

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

Bạn sẽ phải sử dụng phương pháp FindByValue của ListBox

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

+1 này là lựa chọn tốt nhất theo ý kiến ​​của tôi bởi vì nó chỉ lặp qua các mục cần thiết, không phải toàn bộ bộ sưu tập listbox. Tôi đã sử dụng nó trong giải pháp của riêng mình, cảm ơn Phu! –

0

Tôi thích nơi bill berlington đang xảy ra với các giải pháp của mình. Tôi không muốn lặp qua ListBox.Items cho mỗi mục trong mảng của tôi. Đây là giải pháp của tôi:

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

Trong C#:

foreach (ListItem item in ListBox1.Items) 
{ 
    item.Attributes.Add("selected", "selected"); 
} 
Các vấn đề liên quan