Now add a new page to the website.
- Go to the Solution Explorer
- Right-click on the Project name
- Select add new item
- Add new web page and give it a name
- Click OK
Design the page and place the required controls in it. Now drag and drop one TextBox, an Add Button and a Delete Button control on the form. When a user enters some text into a TextBox and clicks on the add Button, text will be shown in the ListBox. After that, select text from the ListBox and click on the Delete Button to remove the text from the ListBox control. Let's take a look at a practical example.
.aspx Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="background-color:Red"
OnClick="Button1_Click" Text="Add" Width="99px" />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server" style="background-color:Orange" Width="255px"></asp:ListBox>
<asp:Button ID="Button2" runat="server" style="background-color:Red"
Text="Delete" Width="134px" onclick="Button2_Click" />
</div>
</form>
</body>
</html>
Now double-click on the Add Button control and add the following code:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text);
}
Now double-click on the Button control delete item and add the following code:
protected void Button2_Click(object sender, EventArgs e)
{
ListBox1.Items.RemoveAt(ListBox1.Items.IndexOf(ListBox1.SelectedItem));
}
In the code-behind write the following code:
Code-behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
ListBox1.Items.RemoveAt(ListBox1.Items.IndexOf(ListBox1.SelectedItem));
}
}
Now run the application and test it.
Now enter text into the TextBox and click on the Add Button to add the items into the list.
Now select an item from the ListBox.
Now press the Delete Button to delete the item from the ListBox.