Search code examples
c#window-management

Disable buttons, depending on where Form is opened from


There's probably an easy solution to this, but I can't find anything on this.I have three forms:

  1. Main Menu
  2. Form 1
  3. Form 2

Both Main Menu and Form 1 can launch Form 2. What I want to do is:

  • if Form 2 is launched from Form 1, some buttons are disabled.

However

  • If Form 2 is launched from Main Menu, everything is enabled.

I know there's a simple solution somewhere, but all I can find is how to open a form, and enable/disable it's parents controls, not open a child form and disable controls before Show() or whatever is called.


Solution

  • You could add a property to the Form2 class like this:

    public bool HideSomeControls
    {
        get;
        set;
    }
    

    Then, right before you show the Form2 in Form1.cs, set that property:

    form2instance.HideSomeControls = true;
    form2instance.Show(); // or ShowDialog, depending...
    

    Then, add a Load event handler to Form2 like this:

    private void Form2_Load(object sender, EventArgs e)
    {
        if (HideSomeControls)
        {
            someControl.Visible = false;
            someOtherControl.Visible = false;
        }
    }
    

    Note that, if MainMenu and Form1 share a single instance of Form2, you'll have to set HideSomeControls to false again in MainMenu before you show the Form2 instance.