50

I'm building a data entry interface and have successfully bound the columns that have reference tables for their data using DropDownList so the user selects from the pre-configured values.

My problem now is that I don't want the first value to be selected by default, I need to force the user to select a value from the list to avoid errors where they didn't pick that field and by default a value was assigned.

Is there a more elegant way of doing this than to add code to include an empty value at the top of the list after I get it from the database and before i pass it to the SelectList constructor in my controller class?

2 Answers 2

99

The Html helper function takes a 'first empty value' parameter as the third argument.

<%=Html.DropDownList("name",dataSource,"-please select item-")%>
Sign up to request clarification or add additional context in comments.

1 Comment

Ah this is great, I was looking at SelectList object params for this
-9

You can also use this way:

dropdownlist.DataTextField = ds.Tables[0].Columns[0].Caption;
dropdownlist.DataValueField = ds.Tables[0].Columns[1].Caption;
dropdownlist.DataSource = ds;
dropdownlist.DataBind();


dropdownlist.Items.Insert(0, new ListItem("Select ...", string.Empty)); 

2 Comments

I guess the question is regarding asp.net MVC!
yep, not applicable to asp.net MVC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.