In this article I will explain how to dynamically add (insert) and remove (delete) items from ListBox control in ASP.Net using C# and VB.Net.
The items will be dynamically added (inserted) and deleted (removed) from ListBox control on Button click in ASP.Net.
HTML Markup
The HTML Markup consists of an ASP.Net ListBox control, a TextBox and two Buttons. I have set the SelectionMode property as Multiple for the ListBox in order to select and delete multiple items.
<asp:ListBox ID="lstFruits" runat="server" Width="150" Height="60" SelectionMode="Multiple">
</asp:ListBox>
<asp:Button Text="Delete" runat="server" OnClick="DeleteValues" />
<br />
<hr />
<asp:TextBox ID="txtFruit" runat="server" />
<asp:Button Text="Add" runat="server" OnClick="AddValues" />
Namespaces
You will need to import the following namespace.
C#
VB.Net
Dynamically adding values to ListBox on Button click in ASP.Net
Inside the Page Load event, a check is made whether a ViewState object containing the dynamic DataTable for populating the ListBox controls exists.
If the ViewState object does not exists then a DataTable containing two columns FruitId and FruitName is created and added to the ViewState object.
Note: The FruitId column is set as AutoIncrement in order to automatically generate unique IDs for the ListBox items.
When the Add button is clicked, the DataTable is fetched from the ViewState object and a new Row is created and added to the DataTable with the value fetched from the TextBox.
After adding the row, the DataTable is saved back in the ViewState object in order to retain the previously added ListBox items across PostBacks.
Finally the DataTable is bound to the ListBox control and which ultimately adds the TextBox value to the ListBox control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Fruits"] == null)
{
DataTable dtFruits = new DataTable();
dtFruits.Columns.AddRange(new DataColumn[2] { new DataColumn("FruitId", typeof(int)),
new DataColumn("FruitName", typeof(string)) });
dtFruits.Columns["FruitId"].AutoIncrement = true;
dtFruits.Columns["FruitId"].AutoIncrementSeed = 1;
dtFruits.Columns["FruitId"].AutoIncrementStep = 1;
ViewState["Fruits"] = dtFruits;
}
}
}
protected void AddValues(object sender, EventArgs e)
{
DataTable dtFruits = (DataTable)ViewState["Fruits"];
dtFruits.Rows.Add();
dtFruits.Rows[dtFruits.Rows.Count - 1]["FruitName"] = txtFruit.Text.Trim();
txtFruit.Text = string.Empty;
ViewState["Fruits"] = dtFruits;
lstFruits.DataSource = dtFruits;
lstFruits.DataTextField = "FruitName";
lstFruits.DataValueField = "FruitId";
lstFruits.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
If ViewState("Fruits") Is Nothing Then
Dim dtFruits As New DataTable()
dtFruits.Columns.AddRange(New DataColumn(1) {New DataColumn("FruitId", GetType(Integer)), _
New DataColumn("FruitName", GetType(String))})
dtFruits.Columns("FruitId").AutoIncrement = True
dtFruits.Columns("FruitId").AutoIncrementSeed = 1
dtFruits.Columns("FruitId").AutoIncrementStep = 1
ViewState("Fruits") = dtFruits
End If
End If
End Sub
Protected Sub AddValues(sender As Object, e As EventArgs)
Dim dtFruits As DataTable = DirectCast(ViewState("Fruits"), DataTable)
dtFruits.Rows.Add()
dtFruits.Rows(dtFruits.Rows.Count - 1)("FruitName") = txtFruit.Text.Trim()
txtFruit.Text = String.Empty
ViewState("Fruits") = dtFruits
lstFruits.DataSource = dtFruits
lstFruits.DataTextField = "FruitName"
lstFruits.DataValueField = "FruitId"
lstFruits.DataBind()
End Sub
Dynamically removing (deleting) multiple items from ListBox on Button click in ASP.Net
When the Delete button is clicked, first the DataTable is fetched from the ViewState object and then a loop is executed over the ListBox items.
Inside the loop, each selected Item is removed from the DataTable based on its FruitId value using the DataTable Select expression.
After removing (deleting) multiple rows, the DataTable is saved back in the ViewState object.
Finally the DataTable is bound to the ListBox control and which ultimately removes (deletes) the multiple selected items from ListBox control.
C#
protected void DeleteValues(object sender, EventArgs e)
{
DataTable dtFruits = (DataTable)ViewState["Fruits"];
foreach (ListItem item in lstFruits.Items)
{
if (item.Selected)
{
DataRow[] rows = dtFruits.Select("FruitId = " + item.Value);
dtFruits.Rows.Remove(rows[0]);
}
}
dtFruits.AcceptChanges();
ViewState["Fruits"] = dtFruits;
lstFruits.DataSource = dtFruits;
lstFruits.DataTextField = "FruitName";
lstFruits.DataValueField = "FruitId";
lstFruits.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim dtFruits As DataTable = DirectCast(ViewState("Fruits"), DataTable)
For Each item As ListItem In lstFruits.Items
If item.Selected Then
Dim rows As DataRow() = dtFruits.Select("FruitId = " & item.Value)
dtFruits.Rows.Remove(rows(0))
End If
Next
dtFruits.AcceptChanges()
ViewState("Fruits") = dtFruits
lstFruits.DataSource = dtFruits
lstFruits.DataTextField = "FruitName"
lstFruits.DataValueField = "FruitId"
lstFruits.DataBind()
End Sub
Screenshot
Demo
Downloads