In this article I will explain how to dynamically add (insert) and remove (delete) items from ListBox command in ASP.Net using C# and VB.Net.

The items will exist dynamically added (inserted) and deleted (removed) from ListBox control on Push click in ASP.Net.

HTML Markup

The HTML Markup consists of an ASP.Internet ListBox control, a TextBox and ii Buttons. I have set the SelectionMode property equally Multiple for the ListBox in club 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 />

< 60 minutes />

< asp : TextBox ID ="txtFruit" runat ="server" />

< asp : Push Text ="Add" runat ="server" OnClick ="AddValues" />

Namespaces

You lot will need to import the following namespace.

C#

VB.Cyberspace

Dynamically adding values to ListBox on Button click in ASP.Net

Inside the Folio Load effect, 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 cavalcade is prepare every bit AutoIncrement in social club to automatically generate unique IDs for the ListBox items.

When the Add together 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.

Subsequently adding the row, the DataTable is saved back in the ViewState object in lodge 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"] == zero)

        {

DataTable dtFruits = new DataTable();

            dtFruits.Columns.AddRange(new DataColumn[ii] { 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 due east)

{

DataTable dtFruits = (DataTable)ViewState["Fruits"];

    dtFruits.Rows.Add together();

    dtFruits.Rows[dtFruits.Rows.Count - one]["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 Every bit Object, e As EventArgs)

If Non IsPostBack And so

If ViewState("Fruits") Is Nothing And so

Dim dtFruits Every bit 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

Terminate If

Cease If

End Sub

Protected Sub AddValues(sender As Object, due east Equally EventArgs)

Dim dtFruits As DataTable = DirectCast(ViewState("Fruits"), DataTable)

    dtFruits.Rows.Add together()

    dtFruits.Rows(dtFruits.Rows.Count - 1)("FruitName") = txtFruit.Text.Trim()

    txtFruit.Text = Cord.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, get-go the DataTable is fetched from the ViewState object and and so a loop is executed over the ListBox items.

Within 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 dorsum in the ViewState object.

Finally the DataTable is bound to the ListBox control and which ultimately removes (deletes) the multiple selected items from ListBox command.

C#

protected void DeleteValues(object sender, EventArgs east)

{

DataTable dtFruits = (DataTable)ViewState["Fruits"];

foreach (ListItem detail 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 Every bit 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))

Cease If

Adjacent

    dtFruits.AcceptChanges()

    ViewState("Fruits") = dtFruits

    lstFruits.DataSource = dtFruits

    lstFruits.DataTextField = "FruitName"

    lstFruits.DataValueField = "FruitId"

    lstFruits.DataBind()

Cease Sub

Screenshot

Add Remove (Delete) Items from ListBox in ASP.Net using C# and VB.Net

Demo

Downloads