Jordan Foreman
Jordan Foreman

Reputation: 3888

Getting value as DateTime, but displaying as DateTime.Year in DropDownList (with LINQ)

In the database, I have a table 'Years', that contains columns for 'YearId', 'YearStart' and 'YearEnd' (don't ask me why, its not my database).

I need to populate an asp:DropDownList with the different year values in the table, ie. I need the dropdown to be like:

//pseudocode
<select>
    <option>2010</option>
    <option>2011</option>
    ..etc..
</select>

But since the 'YearStart' and 'YearEnd' are stored in DateTime format, I'm getting this:

//pseudocode
<select>
    <option>1/1/2010 12:00:00 AM</option>
    <option>1/1/2011 12:00:00 AM</option>
    ..etc..
</select>

Here is how I am currently populating the DropDownList:

dropDownList.DataSource = DataContext.Years;
dropDownList.DataValueField = "YearId";
dropDownList.DataTextField = "YearStart";
dropDownList.DataBind();

Basically, I need the dropDownList.DataTextField to be in DateTime.Year form, ie:

//pseudocode
dropDownList.DataTextField = ("YearStart").Year;

So what would be the best way to populate the dropDownList and achieve what I need?

Upvotes: 2

Views: 2043

Answers (4)

nportelli
nportelli

Reputation: 3916

You can get all LINQy but I'd just do: dropDownList.DataTextFormatString = {0:yyyy};

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextformatstring.aspx

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

Assuming you don't want to change the data source itself, I suspect you'd use:

dropDownList.DataTextField = "YearStart.Year";

Basically you provide a binding path, not necessarily just a single property name.

Upvotes: 3

wsanville
wsanville

Reputation: 37516

Try changing your data binding code to just: (using System.Linq of course)

dropDownList.DataSource = DataContext.Years.Select(d => d.Year);
dropDownList.DataBind();

Upvotes: 1

Bala R
Bala R

Reputation: 108967

You can try including DataTextFormatString

dropDownList.DataTextFormatString = "{0:YYYY}";

or

you can tweak the DataSource like this

dropDownList.DataSource = DataContext.Years.Select(y => new {y.YearID, YearStart = y.YearStart.Year})
                                    .ToList();

Upvotes: 4

Related Questions