ListBox控件使用

ListBox 可以通过 ListSelectionMode 设置多选,默认值为 Single,
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
 <head>
 
     <script runat="server">
 
         void AddBtn_Click(Object Sender, EventArgs e)
         {
             if (ListBox1.SelectedIndex > -1) //检查是否有选中项,否则会报错!未将引用指向对象实列
             {
                  if (ListBox2.Items.FindByValue(ListBox1.SelectedItem.Text) == null) //如果2中未存在选中的值
                 {
                      ListItem Item = new ListItem();
                      // Text and Value are swapped.
                     Item.Text = ListBox1.SelectedItem.Value;
                     Item.Value = ListBox1.SelectedItem.Text;
                     ListBox2.Items.Add(Item);
                  }
             }
         }
 
         void DelBtn_Click(Object Sender, EventArgs e)
         {
             if (ListBox2.SelectedIndex > -1) //检查是否有选中项,否则会报错!未将引用指向对象实列

             {
                 ListBox2.Items.Remove(ListBox2.SelectedItem);
             }
         }
 
     </script>
 
 </head>
 <body>
 
     <h3>ListItem Example</h3>
     <p>
     <form runat=server>
     <table>
     <tr><td>
         <asp:ListBox id=ListBox1 Width="100px" runat="server">
             <asp:ListItem Value="Value 1">Item 1</asp:ListItem>//一种添加方式
             <asp:ListItem Value="Value 2">Item 2</asp:ListItem>
             <asp:ListItem Value="Value 3">Item 3</asp:ListItem>
             <asp:ListItem Value="Value 4">Item 4</asp:ListItem>
             <asp:ListItem Value="Value 5" Selected="True">Item 5</asp:ListItem>
             <asp:ListItem Value="Value 6">Item 6</asp:ListItem>
         </asp:ListBox>
     </td><td>
         <asp:button Text="--->" OnClick="AddBtn_Click" runat="server" /><br>
         <asp:button Text="<---" OnClick="DelBtn_Click" runat="server" />
    </td><td>
         <asp:ListBox id=ListBox2 Width="100px" runat="server"/>
     </td></tr>
     </table>
     </form>
 
 </body>
 </html>

你可能感兴趣的:(listbox)