views:

184

answers:

2

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?

A: 

Yeah that's normal behavior for ASP.NET. You manually have to set your SelectedIndex, it doesn't persist for the user on PostBack.

It's annoying, but you should do an index check before the drop-down gets databound. Make a public method for it so you don't have to fool with it again.

treefrog
+1  A: 

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.

Marko