Here, we will learn how to add new item to dropdownlist control from TextBox Control programmatically and how to remove item from DropDownList control programmatically in asp.net with C#.
Here, we will use DropDownList.Items.Add(“ItemName”) for adding a new item to dropdownlist control in .net.
and we use DropDownList.Items.Remove(“ItemName”) method for remove item from Drop[downList control in asp.net.
First, we design asp.net webpage with two TextBox control and Two Button Control and one DropDownList control.
The HTML code for design asp.net page is like:
<table style=”width: 416px”>
<tr>
<td style=”width: 100px; text-align: right”>
Insert Value :</td>
<td style=”width: 100px; text-align: left”>
<asp:TextBox ID=”txtadd” runat=”server”></asp:TextBox></td>
<td style=”width: 100px; text-align: left”>
<asp:Button ID=”btnadd” runat=”server” Font-Bold=”True” Height=”32px” OnClick=”btnadd_Click”
Text=”ADD” Width=”80px” /></td>
</tr>
<tr>
<td style=”width: 100px; text-align: right”>
Remove Value :</td>
<td style=”width: 100px; text-align: left”>
<asp:TextBox ID=”txtremove” runat=”server”></asp:TextBox></td>
<td style=”width: 100px; text-align: left”>
<asp:Button ID=”btnremove” runat=”server” Font-Bold=”True” Height=”32px” OnClick=”btnremove_Click”
Text=”Remove” Width=”80px” /></td>
</tr>
<tr>
<td style=”width: 100px; text-align: right”>
Value :</td>
<td colspan=”2″ style=”text-align: left”>
<asp:DropDownList ID=”Drpvalue” runat=”server” Width=”128px”>
</asp:DropDownList></td>
</tr>
<tr>
<td style=”width: 100px; text-align: right; height: 21px;”>
</td>
<td colspan=”2″ style=”text-align: left; height: 21px;”>
<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True”></asp:Label></td>
</tr>
</table>
The ASP.Net Example of Dropdownlist control output is :
Now, Here we have two TextBox control and two Button Control one for Add Item to DropDownlist and other for Remove Item from DropDownList control.
Write below code for add New Item to DropDownList on ADD Button Click Event:
protected void btnadd_Click(object sender, EventArgs e)
{
if (txtadd.Text != “”)
{
Drpvalue.Items.Add(txtadd.Text);
txtadd.Text = “”;
Label1.Text = “Item Added Successfully !!”;
}
}
The Output of asp.net example is like:
Now, Write the below code on Remove Button Click Event for Remove Item from Dropdownlist control in asp.net
protected void btnremove_Click(object sender, EventArgs e)
{
if (txtremove.Text != “”)
{
Drpvalue.Items.Remove(txtremove.Text);
txtremove.Text = “”;
Label1.Text = “Item Removed Successfully !!”;
}
}
The ASP.Net remove item from dropdownlist control example output is :
I hope this add and remove item to dropdownlist control example in asp.net will help you………