Adding an item in a DropDownList at a certain position

In ASP.NET when you add a new item using a line such as the one below, and there are items already in the DropDownList, you will notice that this one is added at the bottom of the list.

ddlMyList.Items.Add(“The Swan”);
Sometimes you will be able to move this line in your code relative to the other items so that it is added in the position you want. However, most of the time this is not the case. For example if you used DataBind() to bind the DropDownList to a data source, and then you wanted to add a new item to the DropDownList above all the items that were placed by the data binding process, you will not be able to. Even if you use the line mentioned above before the data binding takes place, the DropDownList will be cleared and only the items from the data source will exist.

Enough talking. The solution is to add the additional item after the data binding takes place, but instead of Items.Add() you should use Items.Insert where you can specify the index of the item to insert. If you specify an index of 0, the item will be added at the very top of the list:

ddlMyList.Items.Insert(0, “The Arrow”);
Now if you would also like this item selected simply use the SelectedIndex property.

Leave a Reply

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

Back To Top