top of page

How to Bind Months , Years to a DropDownList in C#?

Updated: Dec 29, 2024

This blog shows a simple snippet of automatic binding Months and Years to a DropDownList in ASP.net.







This blogs will help you to bind years and months in dropdownlist without SQL database.not dynamic bind.

The dynamic bind means bind the dropdownlist from SQL database using SQL statment inside ASP code page.


Tip #1 - Declare System.Globalization


System.Globalization contains classes that define culture-related information, including the language, the country or region, the calendars in use, the format patterns for dates, currency and numbers, and the sort order for strings.


using System.Globalization;


this Methods for using DateTime code inside Asp.net Code Page.


Tip #2 - Method for Binding Months and years in Page Load.


if (!Page.IsPostBack)

{

DD_MonthBind();

DD_yearsBind();

}

this code to bind the dropdownlists when the page start or refreshed .


"Include quotes by experts in your post to add credibility." – SEO specialist

Tip #3 - Method for Binding Months (DD_MonthBind)


DateTimeFormatInfo months = new DateTimeFormatInfo();

for (int i =1; i <13; i++)

{

DropDownList1.Items.Add(new ListItem(months.GetMonthName(i).ToString()));

DropDownList1.Text = DateTime.Now.ToString("MMMM");

}

this code is to bind dropdwonlist with 12 months and select the default value with current Month.


Tip #4 - Method for Binding Years (DD_yearsBind)


int years = DateTime.Now.Year;

for (int x = years -3; x<=years+3; x++)

{

ListItem li = new ListItem(x.ToString());

DropDownList2.Items.Add(li);

}

This code to bind the dropdwonlist with 3 years after current year and 3 years before current year .

Example : current year is 2024 so the dropdownlist will bind years from 2021 to 2027.


Tip #5 - Method for select the default value with current Year


DropDownList2.Items.FindByText(years.ToString()).Selected = true;


This Code to make the default secelect Value as current year.


Summary


From the preceding all examples we have learned how to bind the DropDownList with month names and Years . I hope you understand it.

Comments


bottom of page