Wednesday, May 6, 2009

Bind DropDownList with SqlDataSource and Custom ListItems

I ran into a small problem earlier today and wanted to make a note of it here in case I forget in the future. I have a dropdownlist that contained a list of about 30 locations. I originally hard coded these locations, but found later on that putting them in a sql table would be a good idea. After I did that I set up the dropdownlist to use the table I just created:


<asp:DropDownList ID="ddlUSERFacilityID" runat="server" AutoPostBack="true" DataSourceID="dsFacilities" DataTextField="FacilityName" DataValueField="FacilityID" >


However I needed to add a "- Select One -" for the users that had either old and invalid facility ids or users who just didn't have one at all and I was stumped. Clicking around a google search landed me this dropdownlist property that solved my problem:


AppendDataBoundItems="true"


So the final control ended up looking like this:

<asp:DropDownList ID="ddlUSERFacilityID" runat="server" onChange="chgColor();" OnSelectedIndexChanged="updateStatus" AutoPostBack="true" DataSourceID="dsFacilities" DataTextField="FacilityName" DataValueField="FacilityID" AppendDataBoundItems="true">

<asp:ListItem Value="SelectOne" Selected="True">- Select One -" </asp:ListItem>

</asp:DropDownList>

No comments:

Post a Comment