dotnetdevcsharp
dotnetdevcsharp

Reputation: 3980

Map Enum to user choice checkboxes

At present I have the following

if ((int)dpRepeatType.SelectedValue == (int)Constants.RepeatType.Weekly)
{
                 wrule = new WeeklyRecurrenceRule(Convert.ToDateTime(dtDateStart.Value),WeekDays.Monday, 1);
                _newAppointment.RecurrenceRule = wrule.ToString();

}

On Screen I have 7 checkboxes representing the days of the week. Sunday to Sat My question is WeekDay is an internal enum of telerik rad scheduler based on the following.

My Question is insteads of doing a tone of if statements on individual checkboxes to see which day or days the user has select which can be more than one, how can i do this with linq at present I am doing it with if statements but I am sure there a better way.

[Flags]
    public enum WeekDays
    {
        //
        // Summary:
        //     Specifies none of the days
        None = 0,
        //
        // Summary:
        //     Specifies the first day of the week
        Sunday = 1,
        //
        // Summary:
        //     Specifies the second day of the week
        Monday = 2,
        //
        // Summary:
        //     Specifies the third day of the week
        Tuesday = 4,
        //
        // Summary:
        //     Specifies the fourth day of the week
        Wednesday = 8,
        //
        // Summary:
        //     Specifies the fifth of the week
        Thursday = 16,
        //
        // Summary:
        //     Specifies the sixth of the week
        Friday = 32,
        //
        // Summary:
        //     Specifies the work days of the week
        WorkDays = 62,
        //
        // Summary:
        //     Specifies the seventh of the week
        Saturday = 64,
        //
        // Summary:
        //     Specifies the weekend days of the week
        WeekendDays = 65,
        //
        // Summary:
        //     Specifies every day of the week
        EveryDay = 127
    }
}

This is what the ui is like to what I am trying to achieve.

enter image description here

Upvotes: 2

Views: 443

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

Let's say that the only CheckBox controls in your form are the ones concerning te week days and their Name property follows the pattern below:

CheckBoxMonday
CheckBoxTuesday
...

One solution could be the following one:

WeekDays wd = WeekDays.None;

foreach (CheckBox checkBox in this.Controls.OfType<CheckBox>())
{   
    if (checkBox.IsChecked)
        wd |= (WeekDays)Enum.Parse(typeof(WeekDays), checkBox.Name.Replace("CheckBox", ""));

}

Demo code here.

Upvotes: 3

Related Questions