<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ListItemCollection</title>
</head>
<body>
    <form id="form1" runat="server">
    <h2>Products:</h2>
    <asp:ListBox ID="lstProducts" Width="200" AutoPostBack="true" OnSelectedIndexChanged="lstProducts_SelectedIndexChanged" runat="server">
    <asp:ListItem Text="Hair Dryer"></asp:ListItem>
    <asp:ListItem Text="Shaving Scream"></asp:ListItem>
    <asp:ListItem Text="Electric Comb"></asp:ListItem>
    <asp:ListItem Text="Nail Polish"></asp:ListItem>
    <asp:ListItem Text="French Toast"></asp:ListItem>
    </asp:ListBox> 
    
    <p></p> 
    <h2>Shopping Cart</h2>
    <asp:ListBox ID="lstCart" Width="200" runat="server"></asp:ListBox>
    <br />
    <asp:Button ID="btnRemove" Text="Remove Item" OnClick="btnRemove_Click" runat="server" />
    <asp:Button ID="btnRemoveAll" Text="Remove All" OnClick="btnRemoveAll_Click" runat="server" />
    </form>
</body>
</html><script runat="server">
    void lstProducts_SelectedIndexChanged(Object sender, EventArgs e)
    {
        lstCart.SelectedIndex = -1;
        //for (int i = 0; i < lstCart.Items.Count; i++)
        //{       
        //     if (!lstProducts.SelectedItem.Equals(lstCart.Items[i]))
        //    {
                lstCart.Items.Add(lstProducts.SelectedItem);
        //    }       
        //}
    }    void btnRemove_Click(Object sender, EventArgs e)
    {
        lstCart.Items.Remove(lstCart.SelectedItem);
    }    void btnRemoveAll_Click(Object sender, EventArgs e)
    {
        lstCart.Items.Clear();
    }    </script>上面代码可以添加删除控件,但是添加时会重复添加,注释了的代码是我自己试着加的,本来是想防止添加重复的,但是结果完全添加不了控件了,我对ASP理解不深,还请各位解答,谢谢

解决方案 »

  1.   


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ListBox ID="lstProducts" Width="200" AutoPostBack="true" OnSelectedIndexChanged="lstProducts_SelectedIndexChanged"
                runat="server">
                <asp:ListItem Text="Hair Dryer"></asp:ListItem>
                <asp:ListItem Text="Shaving Scream"></asp:ListItem>
                <asp:ListItem Text="Electric Comb"></asp:ListItem>
                <asp:ListItem Text="Nail Polish"></asp:ListItem>
                <asp:ListItem Text="French Toast"></asp:ListItem>
            </asp:ListBox>
            <asp:ListBox ID="lstCart" Width="200" runat="server"></asp:ListBox>
        </div>
        </form>
    </body>
    </html>protected void lstProducts_SelectedIndexChanged(object sender, EventArgs e)
            {
                ListBox ls = (ListBox)sender;
                if (lstCart.Items.FindByText(ls.SelectedItem.Text) == null)
                {
                    lstCart.Items.Add(new ListItem(ls.SelectedItem.Text, ls.SelectedItem.Value));
                    ls.Items.Remove(ls.SelectedItem);
                }        }