ASP.NET DropDownList / HTML selection for default selection

For my ASP.NET page, in the code that I load into the DropDownList item various elements / parameters, but I do not set the default value by assigning SelectedIndex. I noticed that for the postback, SelectedIndex is set to 0, even if I never set the focus or changed the value in the DropDownList.

Unless otherwise indicated in the code behind or in the markup, will the default value of 0 be used for SelectedIndex in the postback with a DropDownList? If so, is this part of the HTML standard for picklists, or is it the way it is implemented for ASP.NET?

+3
source share
2 answers

This is normal behavior for an HTML control SELECT.

If the selected property is not used, it always starts with the first element (index 0).

In many cases, I do not want this in ASP.NET, because I specifically want the user to select a parameter.

So what I do is add an empty element that I can check.

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 install a validator that checks if this value is empty, forcing the user to make a choice.

+4
source

, , , Insert Index of 0, SO. , DataBind()

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

myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
+1

Source: https://habr.com/ru/post/1755208/


All Articles