четверг, 10 декабря 2009 г.

How Do I Add an Additional Item To a Databound DropDownList Control in ASP.NET?

It's a common practice to bind some data to a DropDownList or ListBox control. The data for these controls can come from a wide variety of DataSources including Arrays, ArrayLists, HashTables and DataSets. Quite often, though, you'll have the need to add an additional item to the beginning of the list.

This item often instructs your user to select an item from the list, as you can see in the following screenshot:

A drop-down list with the first item instructing the user to select an item

The list with countries is preceded by an item with the text Please select a country. Since this item is usually not present in the datasource, you'll have to add it either manually programmatically through some code.

ASP.NET 2.0 and Later

In ASP.NET 2.0 and onwards things are much easier. The DropDownList control and other list controls now have a AppendDataBoundItems property. With this property set to true, a call to DataBind leaves all existing items in the list. That allows you to add the extra items declaratively in the markup:

<asp:dropdownlist id="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:listitem value="">Please select a country</asp:ListItem>
</asp:DropDownList>

That's it. No more messing around with code in the code behind to add the item. Just setAppendDataBoundItems to true and the manually added item stays where it was.

Комментариев нет: