Wednesday, January 24, 2007

Drop Down List - Show Month Name and Year

Problem:
populate ddl with MonthName and Year with the previous 12 months

Solution:
private void InitializeStartDate(System.Web.UI.WebControls.ListControl lc)
{

//clear out list control
lc.Items.Clear();

DateTime start = DateTime.Now;
DateTime workDate = new DateTime(start.Year, start.Month, 1);

int months = 0;
while (months < 12)
{
ListItem li = new ListItem();

//format display {$MonthName} {$Year} i.e January 2006
li.Text = string.Format("{0:MMMM} {1:yyyy}",workDate,workDate);

//get value of display date
li.Value = workDate.ToShortDateString();

//assign ListItem to DropDownList
lc.Items.Add(li);

//decrement workDate by one month
workDate = workDate.AddMonths(-1);

//increment number of items counter
months++;
}
}

No comments: