muttley91
muttley91

Reputation: 12674

Add a blank value for the first entry of a DropDownList

I have a DropDownList that is data bounds to a SQL Server Data Source. As it is, the first entry from the data source is the first entry selected by default. In order to select this entry (and have the DropDownList_SelectedIndexChange() function be called), I have to select the second option, and then the first option again.

Is there a way to enter an invalid item into the DropDownList as the first item, sort of as a "default value"?

Upvotes: 2

Views: 13343

Answers (2)

Kevin Kunderman
Kevin Kunderman

Reputation: 2134

Set AppendDataBoundItems to true on the drop-down list and then add your default item to the list

<asp:DropDownList ID="ddlOne" runat="server" AppendDataBoundItems="True" 
        DataSourceID="" DataTextField="" DataValueField="">
            <asp:ListItem Value="">Please Select</asp:ListItem>
</asp:DropDownList>

This will result in all your data-bound values being added to the dropdown after the ones you have specified in the markup above

Upvotes: 7

David
David

Reputation: 218808

By "SQL Server Data Source" I assume you mean a declarative SQLDataSource in the page markup, so that there's no actual C# code in question here? If so, there are two things you'd need to do.

First, add a default value to the DropDownList. Second, set the property AppendDataBoundItems to true:

<asp:DropDownList ID="someID" runat="server" DataSourceID="someDataSource" DataTextField="name" DataValueField="id" AppendDataBoundItems="true">
    <asp:ListItem></asp:ListItem>
</asp:DropDownList>

Upvotes: 1

Related Questions