asp.net 和 c# 在下拉列表中禁用上个月

asp.net and c# disable previous month in dropdownlist

我想在 C# 中禁用下拉列表中的前几个月,仅当月份是当前月份时。

例如,如果我今天是 2020 年 9 月,我想禁用从 2020 年 1 月到 8 月 select 的功能,我希望它能够从 9 月/10 月/select 2020 年 11 月/12 月。

请帮我解决这个问题

这是我在后端使用的代码:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack )
        {
            DD_Monthbind();
        }
    }

    private void DD_Monthbind()
    {
        DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
        for (int i = 1; i < 13; i++)
        {       
            DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));       

        }
    }
}

正如其他人在评论中暗示的那样,省略不需要的 drop-down 值而不是禁用它们通常更好(至少从可用性的角度来看):

private void DD_Monthbind()
{
    DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
    int currentMonth = DateTime.Now.Month;

    for (int i = 1; i < 13; i++)
    {
        bool isMonthInPast = i < currentMonth;

        if (!isMonthInPast)
            DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));       
    }
}

如果您真的想禁用这些值,可以使用JavaScript 或CSS 来实现。例如(这是jQuery):

$(/* drop-down value selector */).prop('disabled', true);