tags:

views:

37

answers:

1

I want to have dropdownlist with months and years from some point in the past to the current month. This is my code:

for (int year = 2009; year <= DateTime.Now.Year; year++)
{
   for (int month = 1; month <= 12; month++)
   {
      DateTime date = new DateTime(year, month, 1);
      this.MonthsCombo.Items.Add(
          new RadComboBoxItem(date.ToString("Y"), 
                              String.Format("{0};{1}", year, month))); // this is for reading selected value
   }
}

How to change that code so the last month would be current month?

+2  A: 

Only add the value if ity is less than Today.

if (date <= DateTime.Today)
{
    this.MonthsCombo.Items.Add( 
          new RadComboBoxItem(month.ToString("Y"),  
                              String.Format("{0};{1}", year, m))); // this is for reading selected value 
}

Alternatively, I would make of a while loop, something like

DateTime startDate = new DateTime(2009, 01, 01);
while (startDate <= DateTime.Today)
{

    startDate = startDate.AddMonths(1);
}
astander
@astander: `else break;` might help too.
shahkalpesh
That is true, see the edited version.
astander
loop is fine although it should be startDate = startDate.AddMonths(1); otherwise it is infinite loop
jlp
Correct, fixed that X-)
astander