ListBox: How to Add & Delete items from ListBox in Asp.Net(c#)?

Aman Sharma
In this article we will learn how to insert and delete items from listbox control in using c#. This article is very useful for learning point of view for beginners.

Click on image to Enlarge View

Follow these steps:
   1.       Create a Website in visual studio and add a webform.
   2.       Now place one listbox control, Textbox and two buttons on webpage.
   3.        Now write the code to insert & Delete Items to Listbox on button OnClick event.

Design Section:

        <asp:ListBox ID="lstBox" runat="server" Width="150px"></asp:ListBox>
        <br />
        <br />
        <asp:TextBox ID="txtAdd" runat="server" Width="145px"></asp:TextBox>
        <br />
        <asp:Button ID="btnAdd" runat="server" Text="Add" BackColor="#009933" ForeColor="White" OnClick="btnAdd_Click" />
        <asp:Button ID="btnDelete" runat="server" Text="Delete" BackColor="#FF3300" ForeColor="White" OnClick="btnDelete_Click" />

Write code on btnAdd & btnDelete OnClick Event:

protected void btnAdd_Click(object sender, EventArgs e)
        lstBox.Items.Add(new ListItem(txtAdd.Text));
        txtAdd.Text = string.Empty;
    protected void btnDelete_Click(object sender, EventArgs e)
        List<ListItem> lstSelectedCities = new List<ListItem>();
        foreach (ListItem liItems in lstBox.Items)
            if (liItems.Selected == true)
        foreach (ListItem liSelected in lstSelectedCities)


Post a Comment

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !