In
this article we will learn how to insert and delete items from listbox control
in asp.net 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:
<div>
<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" />
</div>
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)
{
lstSelectedCities.Add(liItems);
}
}
foreach (ListItem liSelected in lstSelectedCities)
{
lstBox.Items.Remove(liSelected);
}
}