Found Somehow
Solutions I've found to my most frustrating coding and computing questions
 
 

Saturday, August 30, 2008

Adding an item to a Databound DropDownList


There's a few reasons why you might want to add an extra item to a databound dropdownlist. For me, I just wanted to add a prompt at the top. I have a drop down list that allows the user to choose an office in a particular city. I want the first item to read "Choose an office..." or something of the sort.

In ASP.NET 2.0, one way to do this is to add an item on page load:
protected void Page_Load(object sender, EventArgs e)
{

ListItem li = new ListItem("Offices:", null);
OfficesDropDown.Items.Add(li);
}

The problem is, when the data is bound, it overwrites the item(s) you've added on page load.

The solution is quite simple. You need to add AppendDataBoundItems="true" to your DropDownList control.
<asp:DropDownList ID="OfficesDropDown" AppendDataBoundItems="true" runat="server" DataSourceID="OfficesSource" DataTextField="Office" DataValueField="Office">

</asp:DropDownList><asp:SqlDataSource ID="OfficesSource" runat="server" ConnectionString="<%$ ConnectionStrings:vd31653_dbConnectionString %>"

SelectCommand="SELECT [Office], [OfficeID] FROM [Offices]"></asp:SqlDataSource>

Note that you cannot add AppendDataBoundItems="true" to a control skin. You need to add this per control.

Thanks to SPAANJAARS.COM for this solution.

Labels: ,