views:

1184

answers:

3

I'm trying to create a LinqDataSource to bind to a DropDownList in an ASP.NET form. I only want to show the elements according to a date (which is one of the fields in the database).

Basically, the elements I want to show are the ones that will happen in the futures (i.e. after DateTime.Now).

I was trying the following markup :

<asp:DropDownList runat="server" ID="DropDownList1" 
    AppendDataBoundItems="True" DataSourceID="LinqDataSource1"
    DataTextField="TextField" DataValueField="ValueField">
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
    ContextTypeName="DataContext1" TableName="Table" 
    Where="DateField &gt;= @DateField">
    <WhereParameters>
        <asp:Parameter DefaultValue="DateTime.Now" Name="DateField" 
            Type="DateTime" />
    </WhereParameters>
</asp:LinqDataSource>

I'm getting a format exception saying that "The string was not recognized as a valid DateTime" when I try to run it. However, the dates in my database seem to be fine, because a DateTime.Parse works perfectly on them. The DateField is of type datetime in SQL.

What am I missing here?

Thanks!

+1  A: 

I suspect it is failing on the DefaultValue.

leppie
+1  A: 

Try:

DefaultValue="<%# DateTime.Now %>"
Andomar
Put me in the right direction. However, you can't use an expression on a Parameter. See my answer for more details.
Hugo Migneron
+3  A: 

The DefaultValue was what was wrong with the code as was suggested by the others.

However, setting the DefaultValue to

 "<%# DateTime.Now %>"

like Andomar suggested (which would make the markup look something like this :

<WhereParameters>
                <asp:Parameter DefaultValue="<%# DateTime.Now %>" Name="DateField" Type="DateTime" />
</WhereParameters>

will not work either because DataBinding expressions are only supported on objects that have a DataBinding Event, and neither Parameter or ControlParameter have one.

For a String, it's fairly easy to create a TextBox or Label and put the <%# %> expression in the value of that new field (more details here), but it was a bit more complicated with a DateTime value, as comparing an SQL DateTime with a .NET DateTime caused an exception.

It can be done quite easily in the Page_Load event by using

DataContext DataContext1 = new DataContext();

    var c = from a in DataContext1.Field
            where a.DateField >= DateTime.Now
            select a;
    DropDownList.DataSource = c;
    DropDownList.DataBind();
Hugo Migneron