开发者

populate drop down list with month/year

I have a date and I need to populate a drop-down with the months/years between that date and today. For instance, if that date is 10/14/2010 then the drop-down should contain October 2010, November 2010, December 2010, January 2011.

The way I'm thinking of doing this is to pass that date to a function, loop from today backwards step 1 month while adding each month to 开发者_如何学编程a collection until we reach that date and finally return a collection of strings. Then, populate the drop-down control on page load. Finally, use some ajax with a page method to parse back the string and trigger a partial page reload.

I'm just wondering if there's an easy way to do it.

Thanks.


Maybe you can try this:

static IEnumerable<DateTime> monthsBetween(DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month + 1))
                         .Select(m => new DateTime(startDate.Year, startDate.Month, 1).AddMonths(m));
    }

This will not give you the result in the exact format that you want, but you get the drift. :)


You can do something like this which is pretty much what you described except counting forward:

private string[] FillDropDownWithDates(DateTime dt)   
{
        DateTime dtnow = DateTime.Now;

        List<string> values =  new List<string>();

        if ( (dt <= dtnow))
        {
            values.Add(String.Format("{0:y}", dt));
        }
        while ( (dt = dt.AddMonths(1)) <= dtnow || ( dt.Month == dtnow.Month && dt.Year == dtnow.Year) )
        {                
            values.Add(String.Format("{0:y}", dt));  // "March, 2008"                     YearMonth
        }


        return values.ToArray();

    }


public static List<string> GetMonths(DateTime StartDate)
  {
   List<string> MonthList = new List<string>();
   DateTime ThisMonth = DateTime.Now.Date;

   while (ThisMonth.Date > StartDate.Date)
   {
    MonthList.Add(ThisMonth.ToString("MMMM") + " " + ThisMonth.Year.ToString());
    ThisMonth = ThisMonth.AddMonths(-1);
   }

   return MonthList;
  }


For Year,

public static IEnumerable<int> Range (int start, int count)
{
    int end = start + count;

    for (int i = start; i < end; i++) 
        yield return i;
}

var startYear = 2000;
YearDropDownList.ItemsSource= Enumerable.Range(startYear, 2050 - startYear + 1);

For Month, An enumerable list with .ToString("MMMM") format.


This is how I got a 12 month/year. Hope the code helps.

public IEnumerable<SelectListItem> Additional12Months {
    get
    {
       return Enumerable.Range(12, 12).Select(i => new SelectListItem { Value = DateTime.Now.AddMonths(-(i)).ToShortDateString(), Text = DateTime.Now.AddMonths(-(i)).ToString("MMM-yyyy") }).ToList();                
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜