Add a Default ListItem to DropDownList after Databind

by Edward 09 August 2010 22:20

We often want the first option in a dropdown list to be the default item selected. However this can be tricky if you are binding your dropdown list to DataSources like Arrays, ArrayLists, HashTables, DataSets and DataTables. If your preferred option is not available from the list, you will need to add it manually to the list of options. You might prefer to have "Please Select" as the first item in the list. This can be easily done, by binding the dropdown list first, and after the DataBind method, insert a new ListItem as in the example below.

//dsNames already populated from database
ddlNames.DataSource = dsNames
ddlNames.DataTextField="Name";
ddlNames.DataValueField= "Id";
ddlNames.DataBind();

//Add listitem to list and select by default
ddlNames.Items.Insert(0, new ListItem("Please Select", String.Empty));
ddlNames.SelectedIndex = 0;

Tags: , ,

ASP.NET

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List