Karlx Swanovski
Karlx Swanovski

Reputation: 2989

Enable control of form based on form it was loaded?

How to enable control of a form based in form it was loaded?

For example if Form3 was open from Form1 the button that will be enable in Form3 is button1 and if Form3 was open from Form2 the button that will be enable in Form3 is button2.

Upvotes: 0

Views: 170

Answers (3)

Robert
Robert

Reputation: 2523

What he means is if you have a form that is of type Form than you wouldn't know which form is the parent if you only look at types.

Form1 opens Form3 and both forms are of type System.Windows.Forms Form2 opens Form3 and both forms are of type System.Windows.Forms

If all three forms have different types than you can check if types are different. Otherwise you have to check names.

form1.Name = "form1";
form2.Name = "form2";
form3.Name = "form3";

You will open child forms from within form1 with

form3.ShowDialog(this);

In form3 you can check for parent form and check for it's name. If it's form2 do something otherwise do something else.

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

Yes you can, just set the Owner of the Form3 when you Show it, then in Form3's Load EventHandler check the Type of the Owner to determine which button to enable. Something like this should work.

Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form3 frm3 = new Form3();
        frm3.Show(this);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2(); //Show Form2 for Testing
        frm2.Show();
    }
}

Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form3 frm3 = new Form3();
        frm3.Show(this);

    }
}

Form3

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        if (Owner == null) return; //Check to make sure there is an Owner
        if (Owner.GetType() == typeof(Form1))
            button1.Enabled = true;
        else if (Owner.GetType() == typeof(Form2))
            button2.Enabled = true;
    }
}

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48076

I think if (typeof(ParentForm) == typeof(Form1)) will do what you want. Keep in mind this check is based purely on the type so if you have multiple instances of Form1 you could run into some problems.

Upvotes: 0

Related Questions