首页 > 解决方案 > 使用月份名称动态绑定下拉列表

问题描述

我在我的网页中放置了一个下拉列表,然后添加以下代码以将项目绑定到页面加载事件中的下拉列表。

在这种情况下,是一个带有月份名称的下拉列表。

当月份更改时,在此下拉列表中,不再显示之前的月份,并且在下个月的 20 日之后不再显示上个月。

我怎样才能从列表中排除列表中的月份之后的月份?

例如

此时在下拉列表月份列表中,我包含从 2 月到 12 月的月份

在二月的第二十天之后,我将在下拉列表中包含从三月到十二月的月份

问题是在下拉列表月份中只看到 3 月,而看不到接下来的几个月(从 4 月到 12 月......)

public partial class DD_Monthbind : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Monthbind();
        }
    }

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

        for (int i = 1; i < 13; i++)
        {
            bool isMonthInPast = ((i + 1) < currentMonth) || (i + 1 == currentMonth && DateTime.Now.Day > 20);

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

更新

private void Monthbind()
{
    DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
    int currentMonth = DateTime.Now.Month;
    for (int i = 1; i < 13; i++)
    {
        bool isMonthInPast = (i < currentMonth) || (i == currentMonth && DateTime.Now.Day > 20);
        if (!isMonthInPast)
        {
            DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));
        }
    }
    foreach (ListItem item in DropDownList1.Items)
    {
        if (DropDownList1.Items.IndexOf(item) != 0)
        {
            item.Enabled = false;
        }

    }
}

在此处输入图像描述

标签: c#asp.netwebformsdropdown

解决方案


推荐阅读