sindrem
sindrem

Reputation: 1231

Add one year with months to dropdownlist

I'm stuck at trying to generate a dropdownlist where i have both year and month showing.

The dropdown must have 1 year showing like below.

That should be one year of months.

I'm using this javascript to submit on the dropdownlist:

$('.dropdownMonthYear').change(function ()
        {
            var values = $('.dropdownMonthYear').val().split(",");
            var month = values[0];
            var year = values[1];
            window.location = '/Garage/Top10Cars.aspx?month=' + month + '&year=' + year;
        });

Codebehind:

month = Convert.ToInt32(Request.QueryString["month"]);
            year = Convert.ToInt32(Request.QueryString["year"]);

Anyone know how this can be done?

Upvotes: 2

Views: 1944

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

This is one way using Linq:

var source = Enumerable.Range(0, 12)
    .Select(i =>  new ListItem(DateTime.Today.AddMonths(-1 * i).ToString("MMM yyyy")));
DdlYearMonth.DataSource = source;
DdlYearMonth.DataBind();

The Range is similar to a for-loop. In the Select i'm creating ListItems from the DateTimes (starting today, going back one month each loop). ToString takes a format string which converts the datetime to a string with your specified format.

Standard Date and Time Format Strings

If you also want to set the ListItem's Value property to the month number(f.e. 1 for january):

var source = Enumerable.Range(0, 12)
   .Select(i => DateTime.Today.AddMonths(-1 * i))
   .Select(d => new { Text = d.ToString("MMM yyyy"), Value = d.Month.ToString() });
DdlYearMonth.DataTextField = "Text";
DdlYearMonth.DataValueField = "Value";
DdlYearMonth.DataSource = source;
DdlYearMonth.DataBind();

Upvotes: 4

Related Questions