2010-08-18 218 views
1

我希望从过去的某个时间点到当前月份的月份和年份都有下拉列表。 这是我的代码:如何从过去的月份到当月的月份和年份列表

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 
    } 
} 

如何更改代码,以便在最后一个月将是当前月份?

回答

2

只有当ity小于今天时才添加该值。

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 
} 

或者,我会做一个while循环,像

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

    startDate = startDate.AddMonths(1); 
} 
+0

'别人休息;'也会有所帮助。 – shahkalpesh 2010-08-18 08:20:03

+0

这是真的,请参阅编辑的版本。 – 2010-08-18 08:20:35

+0

循环很好,但应该是startDate = startDate.AddMonths(1);否则是无限循环 – jlp 2010-08-18 08:49:26