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.
I'd provide an extension method on IEnumerable<string>
that prepended an item to the beginning of the list:
public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)
{
return new string[] { item == null ? string.Empty : item }.Union(data);
}
Its sort of linq-y, as it uses the linq extension method Union. Its a little cleaner than doing this:
var result = new string[]{string.Empty}.Union(from x in data select x.ToString());
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"));
}