ASP.NET DropDownList / HTML select list default selection

harrije picture harrije · Jul 18, 2010 · Viewed 29k times · Source

For my ASP.NET page, in the code behind I load various items/options into a DropDownList but I do not set a default by assigning SelectedIndex. I notice for the postback SelectedIndex is set to 0, even if I never set focus to or changed the value in the DropDownList.

If not otherwise specified in the code behind or markup, will a default value of 0 be used for the SelectedIndex in a postback with a DropDownList? If yes, is this part of the HTML standard for selection lists, or is this just the way it is implemented for ASP.NET?

Answer

Marko picture Marko · Jul 18, 2010

This is normal behavior for the HTML SELECT control.

Unless the selected property is used, it will always start at the first item (index of 0).

In many cases, I don't want this in ASP.NET because I specifically want the user to select an option.

So what I do is add a blank item which I can then validate.

i.e.

<asp:DropDownList runat="server" DataSourceID="SomeDS" AppendDataBoundItems="true"> // Notice the last property
    <asp:ListItem Text="Please select an option" Value="" />
</asp:DropDownList>

This way, I can set a validator which checks if the value is blank, forcing the user to make a selection.