LOADING

Follow me

Fill DropDownLists for birth date in ASP.NET
May 2, 2009|Development

Fill DropDownLists for birth date in ASP.NET

I’ve been building a ton of forms lately for various things at work, and I got tired of having to fill and update all of the fields for dropdowns used to collect a registrant birth date, so I worked out a bit of code to do it for me on Page_Init. Now I don’t have to update the pages at all.

C#:
[code='csharp']
protected void Page_Init(object sender, EventArgs e){
// populate the days drop down
for (int day = 1; day < 32; day ++){ ListItem li = new ListItem(); li.Text = day.ToString(); li.Value = day.ToString(); birthDay.Items.Add(li); } // populate the days drop down DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); for (int month = 1; month < 13; month ++){ ListItem li = new ListItem(); li.Text = dtfi.GetMonthName(month) + " (" + month.ToString() + ")"; li.Value = month.ToString(); birthMonth.Items.Add(li); } // populate the years drop down int thisYear = System.DateTime.Now.Year; int startYear = thisYear - 18; for (int year = startYear; year > startYear - 100; year --){
ListItem li = new ListItem();
li.Text = year.ToString();
li.Value = year.ToString();
birthYear.Items.Add(li);
}
}[/code]
HTML

[code=’html’]


Month

Day

Year

[/code]
I simply added a list item for a label for what each dropdown is filled with, and then a simple label at the end to display error response if it isn’t filled out. One thing to note is the year dropdown only display years for those who are 18 years old and older, it would be easy enough to change that though if your use doesn’t have that constraint.

Nothing too fancy but it works great, and as long as the data we collect doesn’t change I don’t have to ever touch the page again to account for a new year.

2 comments
Share

retsoced

2 coments

  • shubhang mathur
    July 6, 2009 at 2:30 am

    this code is suuficient for fresher but i want to fill dropdown with dynamic data like 10 year after and before values

  • July 6, 2009 at 3:11 am

    @shubhang
    for +/- 10 years from current year you could simply change lines 19 & 20 from the code to:

    int startYear = thisYear + 10;
    20.for (int year = startYear; year > startYear – 10; year –){

    if you’re talking about getting it from a user entered value in a text field, FieldName.text would get you the value, then convert it to an int:

    int startYear = Convert.ToInt32(userValue.text);

  • Comments are closed.