Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?
Here's how to add a value at the top of the list. It can be an empty string, or some text.
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Be sure to set the DropDownList's AppendDataBoundItems=True.
Markup:
<asp:DropDownList ID="ddlQualQuestion" runat="server" DataSourceID="sdsQualQuestion" DataTextField="ShortQuestionText" DataValueField="QualificationQuestionKey" AutoPostBack="true" OnSelectedIndexChanged="ddlQualQuestion_SelectedIndexChanged" OnDataBound="ddlQualQuestion_DataBound" />;
Code behind:
protected void ddlQualQuestion_DataBound(object sender, EventArgs e)
{
ddlQualQuestion.Items.Insert(0, new ListItem("", "0"));
}
Taking the solution DOK provided:
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Addtionally, if you don't want to force the user to make a selection you can add a method to the LinqDataSource of your GridView:
OnSelecting="myGridview_Selecting"
Add code behind like this:
protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if (categories.SelectedValue == "-1")
{
e.WhereParameters.Remove("CategoryID");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With