I use drop down menus regularly. They are a very common control on most any website and often we are just getting a list of things out of a database and simply binding them to the drop down so the user can select one.
It’s very easy to bind items to an ASP.NET DropDownMenu. Removing items as well as adding items it just as easy. But what if you need to add items to the DropDownMenu when the list has already been DataBound and you need to ensure that all the items in the DropDown have been sorted (either by the Text or the Value)? This is a little bit tricky, which is why I’ve taken the time to show you how to do it (and so I can use this example next time I need it).
//grab the first item, using this is something like the "-- Select --" item
var firstItem = myDropDownList.Items;
//remove the "-- Select --" item from the drop down menu, you can skip this if it doesn't apply
//insert the item that you want to add to the DropDownMenu, the location doesn't matter but we will just put it at the top
//extract all the Items in the dropdown menu so that we can sort them, notice the OrderBy, in this case we are ordering by the Value of the DropDownMenu list item
var result = myDropDownList.Items.Cast<ListItem>().ToDictionary(ddlItem => ddlItem.Value, ddlItem => ddlItem.Text,StringComparer.OrdinalIgnoreCase).OrderBy(ddlItem => ddlItem.Value);
//bind the DropDownMenu to the sorted Dictionary
myDropDownList.DataSource = result;
//notice we are setting the Value of the Dictionary to the "Text" field of the DropDownMenu
myDropDownList.DataTextField = "Value";
//notice we are setting the Key of the Dictionary to the "Value" field of the DropDownMenu
myDropDownList.DataValueField = "Key";
//add the "-- Select --" item back to the top of the DropDownMen