user3134334
user3134334

Reputation: 15

When I switch between forms some events are not working

Scenario:

I have a Form (Form1) which consists of following elements.

A panel called panel1, four buttons as btnLoadForm2, btnLoadForm3, btnSave, btnDelete.

When I click the btnLoadForm2 or btnLoadForm3 it loads the Form2 or Form3 into panel1 in Form1.

But the Problem is

For exmaple;

When I work with the first loaded Form doesn't matter which one is loaded in the panel (Form2 or Form3) both btnSave and btnDelete events are working. But When I switch the Form non of button events are working.

Code:

// Codes in Form1 which consists of panel1 and all other buttons

   private void btnloadForm2_Click(object sender, EventArgs e)
   {
        var form = panel1.Controls.OfType<Form>().First();

        if (form.Name != "Form2")
        {
            panel1.Controls.Clear();
            Form newForm = new Form2();
            newForm.TopLevel = false;
            newForm.Visible = true;
            panel1.Controls.Add(newForm);
        }
    }

   private void btnloadForm3_Click(object sender, EventArgs e)     
   {
        var form = panel1.Controls.OfType<Form>().First();

        if (form.Name != "Form3")
        {
            panel1.Controls.Clear();
            Form newForm = new Form3();
            newForm.TopLevel = false;
            newForm.Visible = true;
            panel1.Controls.Add(newForm);
        }
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        var form = panel1.Controls.OfType<Form>().First();

        if (form.Name == "Form2")
        {
            Form2 f2 = (Form2)Application.OpenForms.OfType<Form2>().FirstOrDefault();
            f2.Save();
        }

        else if (form.Name == "Form2")
        {
            Form3 f3 = (Form3)Application.OpenForms.OfType<Form3>().FirstOrDefault();
            f3.Save();
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        var form = panel1.Controls.OfType<Form>().First();

        if (form.Name == "Form2")
        {
            Form2 f2 = (Form2)Application.OpenForms.OfType<Form2>().FirstOrDefault();
            f2.Delete();
        }

        else if (form.Name == "Form3")
        {
            Form3 f3 = (Form3)Application.OpenForms.OfType<Form3>().FirstOrDefault();
            f3.Delete();
        }
    }

Please anyone tell me whats wrong with my code..

I'm not going to write the codes in my Form2 and Form3.. all codes are working when the Forms are loaded into the Form1.Panel1 in my first attempt.

Upvotes: 0

Views: 116

Answers (1)

deostroll
deostroll

Reputation: 11975

You are supposed to display the form as opposed to adding it as control to a panel.

so do something like:

newForm.Show();

or

newForm.ShowDialog();

Upvotes: 1

Related Questions