Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a default value in dropdownlist after binding with database

Tags:

I binded my ddl to my database as below, but how can I add a default text on top of the binded values so that it appears as:

Select Color ---> default text Red ---> database value Blue ---> database value Green ---> database value    

Code:

    DropDownList ddlSize = (DropDownList)FormView_Product.Row.Cells[0].FindControl("ddlSize");     CommerceEntities db = new CommerceEntities();      ddlColor.DataSource = from p in db.ProductTypes                                       where p.ProductID == pID                                       orderby p.Color                                        select new { p.Color };     ddlColor.DataTextField = "Color"; 

Thanks!

like image 862
k80sg Avatar asked Jul 08 '11 13:07

k80sg


People also ask

How do I add a default item to DropDownList?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.


1 Answers

After data-binding, do this:

ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code 

Or follow Brian's second suggestion if you want to do it in markup.

You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".

<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" /> 
like image 116
Keith Avatar answered Oct 07 '22 03:10

Keith