Practical-11
Problem Statement
Write a program to Delete Items from Dropdown list and List box.
Solution
To delete items from a Dropdown list and List box in ASP.NET, follow the steps below:
- Create a new ASP.NET Web Application project in Visual Studio.
- Add a new Web Form to the project by right-clicking on the project in the Solution Explorer, selecting "Add" > "Web Form".
- Rename the Web Form to "Default.aspx".
- Open the "Default.aspx" file and design the user interface as per your requirements using HTML and ASP.NET controls.
- Add the following controls to the "Default.aspx" form:
- DropDownList control:
<asp:DropDownList ID="ddlItems" runat="server"></asp:DropDownList> - ListBox control:
<asp:ListBox ID="lstItems" runat="server"></asp:ListBox> - Button control:
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click"></asp:Button>
- DropDownList control:
- In the code-behind file, write the following code in the Page_Load event handler to populate the DropDownList and ListBox controls:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlItems.Items.Add(new ListItem("Item 1", "1"));
ddlItems.Items.Add(new ListItem("Item 2", "2"));
ddlItems.Items.Add(new ListItem("Item 3", "3"));
lstItems.Items.Add(new ListItem("Item 1", "1"));
lstItems.Items.Add(new ListItem("Item 2", "2"));
lstItems.Items.Add(new ListItem("Item 3", "3"));
}
}
- Write the following code in the click event handler of the "btnDelete" button to delete the selected item from the DropDownList and ListBox controls:
protected void btnDelete_Click(object sender, EventArgs e)
{
if (ddlItems.SelectedIndex != -1)
{
ddlItems.Items.RemoveAt(ddlItems.SelectedIndex);
}
if (lstItems.SelectedIndex != -1)
{
lstItems.Items.RemoveAt(lstItems.SelectedIndex);
}
}
- Build and run the application to see the functionality of deleting items from the controls.
This completes the solution for deleting items from a Dropdown list and List box in ASP.NET.