private void GenerateMonth(bool SetCurruntMonth)
{
drpMonth.Items.Clear();
int year = drpYear.SelectedIndex != 0 ? ((drpYear.SelectedValue != "") ? Convert.ToInt32(drpYear.SelectedValue) : DateTime.Now.Year)
: DateTime.Now.Year;
int months = (DateTime.Now.Year == year) ? DateTime.Now.Month : 12;
for (int i = 1; i <= months; i++)
{
drpMonth.Items.Add(new ListItem(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i), i.ToString()));
}
if (SetCurruntMonth == true && DateTime.Now.Year == year)
{
drpMonth.Items.FindByValue(DateTime.Now.AddMonths(-1).ToString()).Selected = true;
}
else
{
drpMonth.SelectedIndex = 0;
}
}
答案 0 :(得分:0)
您的方法应如下所示:
private void GenerateMonth(bool SetCurruntMonth, DateTime currentDate)
{
drpMonth.Items.Clear();
int year = drpYear.SelectedIndex != 0 ? ((drpYear.SelectedValue != "") ? Convert.ToInt32(drpYear.SelectedValue) : currentDate.Year)
: currentDate.Year;
//int months = (currentDate.Year == year) ? currentDate.Month : 12;
int months = 12;
for (int i = 1; i <= months; i++)
{
drpMonth.Items.Add(new ListItem(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i), i.ToString()));
}
if (SetCurruntMonth == true && currentDate.Year == year)
{
if (currentDate.Month > 1)
drpMonth.Items.FindByValue(currentDate.AddMonths(-1).Month.ToString()).Selected = true;
else
drpMonth.Items.FindByValue("1").Selected = true;
}
else
{
drpMonth.SelectedIndex = 0;
}
}
问题是当您尝试在下拉列表中选择它时,您没有检查Month
属性。而是检查完整的日期时间值。
修改:我已修复您的问题,但我还添加了一个额外的日期参数,以便于测试,如果您愿意,可以替换它。
编辑2 :注释掉“月”逻辑,以便所有月份都显示在下拉列表中。
答案 1 :(得分:0)
private void GenerateMonth(bool SetCurruntMonth, DateTime currentDate)
{
drpYear.ClearSelection();
drpMonth.Items.Clear();
int year = drpYear.SelectedIndex != 0 ? ((drpYear.SelectedValue != "") ? Convert.ToInt32(drpYear.SelectedValue) : currentDate.Year) : currentDate.Year;
int months = (currentDate.Year == year) ? currentDate.Month : 12;
int i;
for ( i = 1; i <= 12; i++)
{
drpMonth.Items.Add(new ListItem(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i), i.ToString()));
}
//int month;
if (SetCurruntMonth == true && currentDate.Year == year)
{
if (currentDate.Month >= 1)
{
drpMonth.Items.FindByValue(currentDate.AddMonths(-1).Month.ToString()).Selected = true;
// month = Convert((currentDate.AddMonths(-1).Month.ToString()).Selected = true);
}
else
drpMonth.Items.FindByValue("1").Selected = true;
//drpYear.Items.FindByValue((DateTime.Now.Year-1).ToString()).Selected = true;
if (currentDate.Month == 1)
{
DateTime year1 = (currentDate.AddYears(-1));
int yy = Convert.ToInt16(year1.Year);
enter code here
drpYear.Items.Add(new ListItem(Convert.ToString(year)));
drpYear.SelectedValue= Convert.ToString(yy);
}
}
else
{
drpMonth.SelectedIndex = 0;
}
}