Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - Adding a default value in dropdownlist after binding with database

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...