Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

For anybody looking for a way to do this from the code behind, you can add the extra list item there by using the Insert function and specifying an Index of 0, as mentioned in this SO Question. Just make sure to do so after you've called DataBind()

myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();

myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top