Add List Item from CheckBox List to ListBox in ASP.net (C#)

Here I want to share you how we can add items from CheckBox List to ListBox. It’s very simple just look at the below code and you will get to know how simple it is.
.aspx code:
<fieldset >
    <legend>Add/Remove ListBox Item </legend>
   
    <asp:CheckBoxList ID="cblItems" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">
    <asp:ListItem Value="1">One</asp:ListItem>
            <asp:ListItem Value="2">C#</asp:ListItem>
            <asp:ListItem Value="3">C++</asp:ListItem>
            <asp:ListItem Value="4">Pearl</asp:ListItem>
            <asp:ListItem Value="5">Ruby</asp:ListItem>
            <asp:ListItem Value="6">Python</asp:ListItem>
            <asp:ListItem Value="7">J#</asp:ListItem>
    </asp:CheckBoxList>

    <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="AddItem" />
        <asp:Button ID="bntRemove" runat="server" Text="Remove" OnClick="RemoveItem" />
    <asp:ListBox ID="lstAddedItem" runat="server" SelectionMode="Multiple"></asp:ListBox>

    <asp:Literal ID="ltMessage" runat="server" Visible="false"></asp:Literal>
    </fieldset>

.aspx.cs code:
//On Add Item Click Event
    protected void AddItem(object sender, EventArgs e)
    {
        this.AddListItemFromCheckBoxList(cblItems, lstAddedItem);
        ltMessage.Visible = true;
        ltMessage.Text = "List Item added successfully!";
    }
//On Remove Item Click Event

    protected void RemoveItem(object sender, EventArgs e)
    {
        this.RemoveListItemFromCheckBoxList(lstAddedItem);
        ltMessage.Visible = true;
        ltMessage.Text = "List Item removed successfully!";
    }

//Add List Item From CheckBoxList Item

    protected void AddListItemFromCheckBoxList(CheckBoxList chkList, ListBox lstTobeAdded)
    {
        for (int i = 0; i < chkList.Items.Count; i++)
        {
            if (chkList.Items[i].Selected == true)
            {
                ListItem li = new ListItem();
                li.Value = chkList.Items[i].Value;
                li.Text = chkList.Items[i].Text;
                if (!lstTobeAdded.Items.Contains(li))       //prevent for duplicate item
                {
                    lstTobeAdded.Items.Add(li); //add to list item.
                }
            }
        }
    }

//Remove List Item (selected) From ListBox Item

    protected void RemoveListItemFromCheckBoxList(ListBox lstTobeAdded)
    {
        for (int i = 0; i < lstTobeAdded.Items.Count; i++)
        {
            if (lstTobeAdded.Items[i].Selected == true)     //check if listBox item is selected
            {
                lstTobeAdded.Items.RemoveAt(i); //remove ListBox item from current selection
            }
        }
    }

I hope it will help you out. Feel free to post your comments and feedback.
Cheers,

ved

Comments