首页 > 解决方案 > 如何获得“jan-2018, Feb-2018, Mar-2018”作为下拉列表

问题描述

如何在下拉列表中同时获取月份和年份,月份列表应显示下一个 3 个月列表,例如,如果当前月份是 2018 年 1 月,则下拉列表应显示 2018 年 1 月、2018 年 2 月、2018 年 3 月。

谁能建议我如何实现这一目标?

Jan-2018 
Feb-2018
Mar-2018

标签: c#asp.net

解决方案


一种简单的方法是使用inEnumerable.Range并获取正确的月份名称GetMonthNameDateTimeFormatInfo

DropDownList1.DataSource = Enumerable.Range(1, 12).Select(i => new KeyValuePair<int, string>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(i).Substring(0, 3) + "-" + DateTime.Now.Year)).ToList();
DropDownList1.DataValueField = "key";
DropDownList1.DataValueField = "value";
DropDownList1.DataBind();

DDL 的 value 字段仍然是 1 - 12 的整数,因此您可以轻松地在代码中处理月份。

更新

如果您想从当前月份开始,请使用

Enumerable.Range(0, 11).Select(i => new KeyValuePair<int, string>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(DateTime.Now.AddMonths(i+1).Month).Substring(0, 3) + "-" + DateTime.Now.AddMonths(i).Year)).ToList();

推荐阅读