首页 > 解决方案 > asp.net 和 c# 在下拉列表中禁用上个月

问题描述

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

例如,如果我今天是 2020 年 9 月,我想禁用从 2020 年 1 月到 2020 年 8 月的选择功能,并且我希望它能够从 2020 年 9 月/10 月/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()));       

        }
    }
}

标签: c#drop-down-menu

解决方案


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

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

推荐阅读