Add Default Item to DropDownList
Tuesday, June 13th, 2006In many situations when I am using a DropDownList I need to provide a default option for the user. Perhaps there isn’t a relevant value in the list for them to choose or perhaps the List doesn’t apply. In these situations I like to add a default ListItem with an index of 0 to show that nothing has been selected from the list. It is very easy to add a default option to a bound DropDownList and a nice finishing touch to your page.
//Get your DataSet.
DataSet productList = GetProductList();
DripDownList1.DataTextField = “ProductName”;
DripDownList1.DataValueField = “ProductID”;
DripDownList1.DataSource = productList;
DripDownList1.DataBind();
//Add the default item manually.
DripDownList1.Items.Insert(0, new ListItem(”<Select One>”, “0″))
DataSet productList = GetProductList();
DripDownList1.DataTextField = “ProductName”;
DripDownList1.DataValueField = “ProductID”;
DripDownList1.DataSource = productList;
DripDownList1.DataBind();
//Add the default item manually.
DripDownList1.Items.Insert(0, new ListItem(”<Select One>”, “0″))
Note: Be careful with Page.DataBind(). If you call this method it will rebind your DropDownList and you will lose the item you just manually added. I banged my head against my desk for about an hour before I figured this out.
One Response to “Add Default Item to DropDownList”
Leave a Reply
You must be logged in to post a comment.
October 16th, 2006 at 9:49 am
Just recently learned from a webcast from Fritz Onion that you can use AppendDataBoundItems =true property for the same purpose. Just add the ‘Select xxx’ as the first item and then do the databinding.