How to Add and Insert Item in DropDownList contol in ASP.Net

Here, in this asp.net post we will learn to Add and Insert Item in DropDownlist control in asp.net c#.

First we learn the difference between Add and Insert property of dropdownlist control.

Add – Add property used to Add New Item in DropDownList control at the End of the List means add new Item at last position to the dropdownlist control.

Insert – Insert property used to Insert New Item in DropDownList at Desired specific position in the list.

First we design the asp.net webpage with two TextBox Control and two Button Control and one label control.

The HTML code for design asp.net page is:

<table>
<tr>
<td style=”width: 100px; text-align: right”>
&nbsp;Enter Value :</td>
<td style=”width: 100px; text-align: left”>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox></td>
<td style=”width: 100px; text-align: left”>
</td>
</tr>
<tr>
<td style=”width: 100px; text-align: right”>
&nbsp;</td>
<td style=”width: 100px; text-align: left”>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”ADD” />
&nbsp;
<asp:Button ID=”Button2″ runat=”server” OnClick=”Button2_Click” Text=”INSERT” /></td>
<td style=”width: 100px; text-align: left”>
</td>
</tr>
<tr>
<td style=”width: 100px; text-align: right”>
</td>
<td style=”width: 100px; text-align: left”>
<asp:DropDownList ID=”DropDownList1″ runat=”server” Width=”128px”>
</asp:DropDownList></td>
<td style=”width: 100px; text-align: left”>
</td>
</tr>
<tr>
<td colspan=”3″ style=”text-align: center”>
<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True” ForeColor=”Purple”></asp:Label></td>
</tr>
</table>

The output of asp.net example of add and insert item to dropdownlist is:

add / insert new item to dropdownlist contol in asp.net
add / insert new item to dropdownlist contol in asp.net

Now, write the below code on ADD button for Add new item to Dropdownlist control at last position.

protected void Button1_Click(object sender, EventArgs e)
{
DropDownList1.Items.Add(TextBox1.Text);
Label1.Text = TextBox1.Text + ” Item added to end of list”;
}

The Out put of asp.net add new item to dropdownlist contol is:

Add / Insert new item to dropdownlist control in asp.net
Add / Insert new item to dropdownlist control in asp.net

Write below code on INSERT button for insert new item at specific position in dropdownlist control in asp.net.

protected void Button2_Click(object sender, EventArgs e)
{
DropDownList1.Items.Insert(0, TextBox1.Text);
Label1.Text = TextBox1.Text + ” Item added at position 0″;
DropDownList1.SelectedIndex = 0;
}

The asp.net dropdownlist insert example output like:

Add / Insert new item to dropdownlist control in asp.net
Add / Insert new item to dropdownlist control in asp.net

I hope this asp.net post of add / insert item to dropdownlist control will hepl you…..

Leave a Reply

Your email address will not be published. Required fields are marked *