.NET Tip: Find DayOfWeek from a String or Stupid Enum Tricks
We are working on a project that runs scheduled tasks at user specified times. In short, the user needs to synchronize a local database with a remote one and wanted to automate the process. For context here is the UI that we developed for this iteration…
The bit that leads us to this tip is the ComboBox that handles the potential day of the week to schedule the task. When these options are saved, the day selected gets stored into UserSetting as text (eg. “Monday”, “Tuesday” etc…). At the next launch of the app, we need to read those settings in and convert them to something we can use in our scheduling algorithm. Do do that, we need to convert a text day into a DayOfWeek enumeration object.
1 2 3 4 5 6 7 8 9 10 11 12 13 | DayOfWeek theday; if (Enum.IsDefined(typeof(DayOfWeek), daynameastext)) { // find it, the "true" means to be case insensitive theday = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), daynameastext, true); } else { // handle the error and let someone know the string was invalid // in our example screenshot this would include the text of the words // "Day" or "Never" and thus we also handled those settings here } |
Notice from the typecasts that Enum.Parse is not tied to any specific Enum so you can use it in lots of situations.
Enjoy!


16. Apr, 2010 








No comments yet... Be the first to leave a reply!