Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownList with LinqDataSource and an empty option

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

like image 721
jansokoly Avatar asked Nov 10 '08 16:11

jansokoly


3 Answers

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.

like image 89
DOK Avatar answered Oct 04 '22 02:10

DOK


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"));  
}  
like image 44
Cheryl G Avatar answered Oct 04 '22 02:10

Cheryl G


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");
    }
}
like image 34
jme-mac Avatar answered Oct 04 '22 03:10

jme-mac