Dynamically bind dropdown with months names

I place a drop downlist into my web page, then add following code to bind items to dropdown list within the page load event.

In this case is a drop downlist  with month names.

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

On this drop downlist  when the month changes, the previous month or months are no longer displayed

e.g.

with date 01 February in the list disappears the month of January.

I would need that the previous month is no longer shown after the 10th of the following month

Can you help me?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

please try below change in your code.

bool isMonthInPast = ((i+1) < currentMonth) || (i+1== currentMonth && DateTime.Now.Day>10);

Method 2

I would do something like this. Add the months from the current one and then check if the days are <= 10. If so just insert the previous month.

private void DD_Monthbind()
{
    DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
    DateTime today = DateTime.Now;

    for (int i = today.Month; i <= 12; i++)
    {
        DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));
    }

    if (today.Day <= 10)
    {
        DropDownList1.Items.Insert(0, new ListItem(info.GetMonthName(today.AddMonths(-1).Month), today.AddMonths(-1).Month.ToString()));
    }
}

You can test various dates by changing today

DateTime today = DateTime.Now.AddMonths(5).AddDays(10);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x