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!
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" />
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
You can add it programmatically or in the markup, but if you add it programmatically, rather than Add
the item, you should Insert
it as position zero so that it is the first item:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
The default item is expected to be the first item in the list. If you just Add
it, it will be on the bottom and will not be selected by default.
design
<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />
codebehind
protected void ddlArea_DataBound(object sender, EventArgs e)
{
ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}
The solution provided by Justin should work. To be sure making use of SelectedIndex
property will also help.
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
ddlColor.SelectedIndex = 0;
精彩评论