如何将值动态设置为下拉列表?

如何将值动态设置为下拉列表?

问题描述:

让我们考虑我有两个日期字段。如何将值动态设置为下拉列表?

DateTime dt1 = "01/04/2012" 
DateTime dt2 = "31/08/2012" 

这里我的日期是“DD/MM/YYYY”格式。 这里dt1是开始日期,dt2是结束日期。 从两个日期字段中,我可以知道它位于04,05,06,07,08个月。

所以我想在我的下拉列表中显示月份和年份的组合。

04/2012 
05/2012 
06/2012 
07/2012 
08/2012 

那么请帮我解决如何实现这个目标。

在此先感谢...

+1

你尝试过什么了吗?此外,简单搜索C#和日期时间将为您提供有关如何从日期时间对象获取月份和年份的答案。 – 2012-07-11 10:33:11

类似下面会给你字符串列表,您可以使用绑定到下拉。

DateTime dt1 = DateTime.ParseExact("01/04/2012", "d/M/yyyy", CultureInfo.InvariantCulture); 
DateTime dt2 = DateTime.ParseExact("31/08/2012", "d/M/yyyy", CultureInfo.InvariantCulture); 
List<string> list = new List<string>(); 
while (dt2 > dt1) 
    { 
     list.Add(dt1.Month + "/" + dt1.Year); 
     dt1 = dt1.AddMonths(1); 
     } 

如果输出它使用的foreach您将获得:

foreach (string str in list) 
    { 
     Console.WriteLine(str); 
    } 


4/2012 
5/2012 
6/2012 
7/2012 
8/2012 

以后如果它的ASP.Net(因为你使用的下拉列表),你可以做

DropDownList1.DataSource = list; 
    DropDownList1.DataBind(); 
+0

你真的需要创建一个List吗? – MMK 2012-07-11 11:46:46

+0

@MMK,不,还有其他的替代方案,它只是很容易编码,我想 – Habib 2012-07-11 11:48:15

+0

请检查我的答案是否正确? – MMK 2012-07-11 11:54:05

 DateTime dt1 = new DateTime(2012,04,01); 
     DateTime dt2 = new DateTime(2012,08,30); 

     int firstMonth = dt1.Month; 
     int lastMonth =dt2.Month; 
     //Then you can compare the two numbers as you like 

你可以这样做像这样:

int firstMonth = Int32.Parse(dt1.Month); 
int secondMonth = Int32.Parse(dt2.Month); 
int year = Int32.Parse(dt1.Year); 
// You could do some checking if the year is different or something. 
for(int month = firstMonth; month <= secondMonth; month++) 
    // Add the date to the drop down list by using (month + year).ToString() 

何这有助于!

如果Asp.net:

DateTime dt1 = new DateTime(); 
    dt1 = DateTime.ParseExact("01/04/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture); 
    DateTime dt2 = new DateTime(); 
    dt2 = DateTime.ParseExact("31/08/2012", "dd/M/yyyy", CultureInfo.InvariantCulture); 
    while (dt2 > dt1) 
    { 
     dt1 = dt1.AddMonths(1); 
     this.dateDropDownList.Items.Add(dt1.ToString("MM/yyyy", CultureInfo.InvariantCulture)); 
    } 

如果Windows窗体:

DateTime dt1 = new DateTime(); 
    dt1 = DateTime.ParseExact("01/04/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture); 
    DateTime dt2 = new DateTime(); 
    dt2 = DateTime.ParseExact("31/08/2012", "dd/M/yyyy", CultureInfo.InvariantCulture); 
    while (dt2 > dt1) 
    { 
     dt1 = dt1.AddMonths(1); 
     this.dateComboBox.Items.Add(dt1.ToString("MM/yyyy", CultureInfo.InvariantCulture)); 
    }