Credit Card Expiration Date DropDownList Sample Code
The other day I needed to create a credit card input form including the drop down lists for the credit card expiration month and year. I started to write the code to populate the month and year drop down lists and I wanted to make them dynamic so that whatever the year was it would add an appropriate number of list items. But as I started thinking about how to structure the code, I figured that this has been written probably thousands of times by other developers so I would just Google for it. To my surprise, I was unable to pull back any sample code for my various search terms. In the end I had to write it myself but now I am posting it on my blog so that others my benefit from my hard work. :)
//Populate the credit card expiration month drop down
for (int i = 1; i <= 12; i++)
{
DateTime month = new DateTime(2000, i, 1);
ListItem li = new ListItem(month.ToString("MMM (M)"), month.ToString("MM"));
ExpirationDateMonthDropDown.Items.Add(li);
}
ExpirationDateMonthDropDown.Items[0].Selected = true;
//Populate the credit card expiration year drop down (go out 12 years)
for (int i = 0; i <= 11; i++)
{
String year = (DateTime.Today.Year + i).ToString();
ListItem li = new ListItem(year, year);
ExpirationDateYearDropDown.Items.Add(li);
}
ExpirationDateYearDropDown.Items[0].Selected = true;