2012-07-11 50 views
-1

讓我們考慮我有兩個日期字段。如何將值動態設置爲下拉列表?

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

回答

0

類似下面會給你字符串列表,您可以使用綁定到下拉。

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

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

你可以這樣做像這樣:

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() 

何這有助於!

0

如果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)); 
    } 
相關問題