Tuesday, April 14, 2009

Add empty item to databound drop down list in C# .NET

Do you have a data-bound drop down list, but want to leave the list empty or blank initially? Well, you can, and it's really simple. In your aspx page, where you declare your DropDownList, just make sure to do it as follows:

<asp:DropDownList ID="yourID" runat="server" AppendDataBoundItems="True">
<asp:ListItem Value="" Text="" />
</asp:DropDownList>


The key here is the AppendDataBoundItems="True" property. This allows you to define your own list items, and then any items that are bound to data are added after those items, aka appended.

You can find the original post at http://stackoverflow.com

However, if you find that you're getting the same items added multiple times you can do it this way instead. Leave AppendDataBoundItems="False" and rather add the empty/blank entry programmatically. To do that add the following code after your drop-down has been filled

DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList1.SelectedIndex = 0;

This will add an empty/blank entry at index zero of your dropdown box, and also make sure that it is the selected value. If you don't want to change it to the selected value don't use the second line. I found this on http://stackoverflow.com as well

2 comments:

Anonymous said...

DropDown List Control

Anonymous said...

Thank You!!!

This helped me with my web application in Visual Basic.