Question : C # Enums Switch statement

Hello All,

I'm trying to do my uni assignment with a enum switch statement instead of having loads of "if" statements.
I know that it is better code to do it with the switch statement, but I'm gtting stuck.

This is my code:

public enum Activities
            {
                Running,
                Cycling,
                Walking,
                Swimming,
                Climbing,
                Skiing,
                InLineSkating,
            }
       
        private static string GetActivity(Activities types)
        {

            string running, cycling, walking, climbing, swimming, skiing, inLine;
            string personActivity = Activity;

            switch (types) {
                case chkRunning.Checked:
                    running = "running\n";
                    break;
                   
                case chkCycling.Checked:
                    cycling = "cycling\n";
                    break;

                case chkWalking.Checked:
                    walking = "walking\n";
                    break;

                case chkClimbing.Checked:
                    climbing = "climbing\n";
                    break;

                case chkSkiing.Checked:
                    skiing = "skiing\n";
                    break;

                case chkInLine.Checked:
                    inLine = "In-Line Skating\n";
                    break;
                                           
            }
        }

So the thing is:
I have multiple check boxes with the acitvities listed under "public enum Activities" and I'd like to list all the ones that have been selected on a messagebox.show(activieties);

Please help.

Thanks.
Ampletrix

Answer : C # Enums Switch statement

Hi mate,

If you want to itterate through the checkboxes and inform the user via MessageBox which ones are checked you can use this piece of code. It roughly demonstrates how to itterate through controls of typ CheckBox.

private void button1_Click(object sender, EventArgs e)
        {
            string chckd = "";
            foreach (Control ctr in groupBox1.Controls.OfType<CheckBox>())
            {
                if (((CheckBox)ctr).Checked == true)
                {
                    chckd += ((CheckBox)ctr).Text + ", ";
                }
            }

            chckd += "are checked!";

            MessageBox.Show(chckd);
        }


Please note I put them inside GroupBox so its easier for me to itterate. You can than use your piece of code in this event to fetch the activity depending on the text that is set next to the CheckBox.

Tell me if this helps.

Regards
Random Solutions  
 
programming4us programming4us