2009-07-01 41 views

Respuesta

6

El código VB para hacerlo ...

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

Aquí hay un C# muestra


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

(código subyacente)

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

Usted tendrá que utilizar el método FindByValue del ListBox

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

+1 esta es la mejor opción en mi opinión, ya que sólo itera a través de los artículos que se necesitan, no toda la colección cuadro de lista. Lo usé en mi propia solución, gracias Phu! –

0

me gusta donde bill berlington va con su solución. No quiero iterar a través de ListBox.Items para cada elemento en mi matriz. Aquí está mi solución:

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

En C#:

foreach (ListItem item in ListBox1.Items) 
{ 
    item.Attributes.Add("selected", "selected"); 
} 
Cuestiones relacionadas