Auto-Populating Drop Down List

Share |

Sometimes I write a little C# code. Not as much as I would like, but I like the challenge. Today’s challenge was to populate a drop-down list with the dates of the next 10 Wednesdays. Sounds simple enough, but I did get caught on one thing – the AddDays() method. Fortunately I found this, and my drop-down was populated:

// Get the current day
DateTime today = DateTime.Now;
bool isWed = today.DayOfWeek == DayOfWeek.Wednesday;
while (!isWed){
    today= today.AddDays(1);
     isWed = today.DayOfWeek == DayOfWeek.Wednesday;
}
// add to the first Wednesday
 DateAttending.Items.Add(new ListItem(today.ToLongDateString(), today.ToShortDateString()));
// Now add 9 more
for (int i = 0; i < 9; i++)
{
      today = today.AddDays(7);
      DateAttending.Items.Add(new ListItem(today.ToLongDateString(), today.ToShortDateString()));
}

Works great, and the client was very impressed (they had been updating the drop down list by hand on their old website)



Leave a Reply