views:

1103

answers:

3

Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?

+5  A: 

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.

DOK
Why don't you add that suggestion to your sample code for clarity?
Keltex
Thanks for the suggestion, Keltex. I thought my original version emphasized the point that the attribute had to be changed, but obviously it didn't.
DOK
As it turns out, just setting AppendDataBoundItems to true adds an empty option to the beginning. Like if it was there by default or what. If I add an asp:ListItem, I'll get 2 empty options. Anyway, your solution is cool, thank you.
cruster
Thanks for the info, custer. I didn't know that.
DOK
A: 

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());
Will
A: 

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"));
}

Cheryl G