Search code examples
c#.netwinformswindowcommand

Controlling order of commands using buttons


In Windows form I have Button1, Button2 and Button3. These buttons represent a series of actions that should be carried out in a order from starting action to final action. So that normally I can handle this as follows.

Form1: Form
{

    Form_Load(Object sender, event Args e)
    {
        Button1.Enabled = true;
        Button2.Enabled = false;
        Button3.Enabled = false;
    }


    Button1_click(Object sender, event Args e)
    {
        //Actions
        Button2.Enabled = true;
        Button1.Enabled = false;
    }

    Button2_click(Object sender, event Args e)
    {
        //Actions
        Button3.Enabled = true;
        Button2.Enabled = false;
    }

    Button3_click(Object sender, e)
    {
        //Actions
        Button3.Enabled = false;
        Button1.Enabled = true;
    }
}

In several places I'm doing it in this way. Is this the standard way?

EDIT:

And also in a simple situation like you should have clicked button1 before clicking button2, the above approach is acceptable?


Solution

  • To expand on what Bjarke said, I'm providing a code example.

    Form1: Form
    {
        List<Button> listButtons = new List<Button>();
    
        public void EnableButton(Button btnToEnable)
        {
            foreach(Button btn in listButtons)
            {
                //check button name.
                //if it is the button to enable, enable it, if not then disable it
                btn.Enabled = btn.Name == btnToEnable.Name;
            }
        }
    
        Form_Load(Object sender, event Args e)
        {
            listButtons.Add(Button1);
            listButtons.Add(Button2);
            listButtons.Add(Button3);
    
            EnableButton(Button1);
    
            //Button1.Enabled = true;
            //Button2.Enabled = false;
            //Button3.Enabled = false;
        }
    
    
        Button1_click(Object sender, event Args e)
        {
            EnableButton(Button2);
            //Actions
            //Button2.Enabled = true;
            //Button1.Enabled = false;
        }
    
        Button2_click(Object sender, event Args e)
        {
            EnableButton(Button3);
            //Actions
            //Button3.Enabled = true;
            //Button2.Enabled = false;
        }
    
        Button3_click(Object sender, e)
        {
            EnableButton(Button1);
            //Actions
            //Button3.Enabled = false;
            //Button1.Enabled = true;
        }
    }