Hello everyone,
In my drop down list ddlmonth I need to display the months between August to December for the year 2024, while for 2025 I need to display all the months progressively with respect to the current month.
I mean:
if we are in February 2025, I only need to display the month of January 2025, if we are in March 2025 I need to display the months of January and February 2025, if we are in April 2025 I need to display the months of January, February and March 2025, etc.
Today, March 2025 I tried this code but I only see February 2025 and January 2025 has disappeared
DateTime dateTime = DateTime.Now;
List<ListItem> months = new List<ListItem>();
 
if (ddlyear.SelectedValue == "2024")
{
    for (int i = 2; i <= 8; i++)
    {
        months.Add(ddlmonth.Items.Cast<ListItem>()
                        .Where(x => x.Value.Equals(dateTime.AddMonths(-i).Month.ToString()))
                        .FirstOrDefault());
    }
}
else
{
    for (int i = 1; i <= 2; i++)
    {
 
        months.Add(ddlmonth.Items.Cast<ListItem>()
                        .Where(x => x.Value.Equals(dateTime.AddMonths(-i).Month.ToString()))
                        .FirstOrDefault());
    }
}
 
//Determines first item i.e.Equals Default Item.
ListItem defaultItem = ddlmonth.Items[0];
 
//Clears all items in the DropDownList.
ddlmonth.Items.Clear();
 
//Reverse the List of last two months.
months.Reverse();
 
//Inserts Default Item.
months.Insert(0, defaultItem);
 
//Assigning month to DropDownList.
ddlmonth.DataSource = months;
ddlmonth.DataTextField = "Text";
ddlmonth.DataValueField = "Value";
ddlmonth.DataBind();