user2269364
user2269364

Reputation: 77

Open a new Form from another Form whith ALL componentns

Im trying to open a new form on a click on the main form. The problem is the the new form oppens up but whithout any component, just embty form this is what i wrote.

private void button2_Click(object sender, EventArgs e)
    {
        Form rr = new Form();
        this.Hide();
        rr.ShowDialog();

    }

Upvotes: 0

Views: 64

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Problem : it is because you are just creating and displaying the new Form without adding controls on it.

Method 1 : You can Add controls to the Form created at runtime.

Try This: Adding Label on Form -similarly you can add other controls.

        Form rr = new Form();
        Label l1=new Label();
        l1.Text = "label 1";
        rr.Controls.Add(l1);
        this.Hide();
        rr.ShowDialog();

Method 2 : you can create the NewForm from IDE and add then add controls from DesignView.

Adding Form from Visual Studio IDE:

1. Right click on project
2. Select Add -> Windows Form...
3. Now Enter form your formname -> SampleForm
4. Now Add the controls on the newly created SampleForm
5. Display the newly created Form

SampleForm sample=new SampleForm();
sample.ShowDialog();

Upvotes: 0

SHM
SHM

Reputation: 1952

i have a little helper function witch is this:

  private void ShowForm<T>() where T: Form, new ()
    {
        this.Hide();
        T form = new T();
        form.FormClosed += (s, e) => this.Show();
        form.Show();
    }

this is the main form witch works like a storyboard and for example when some one click a button and im going to display a new form i do this:

    private void SomeButton_Click(object sender, EventArgs e)
    {
        ShowForm<PublishersForm>();
    }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

That's because you're opening basic Form but not your form (that is with controls).

Suppose your form class (which you've designed) is MyForm, so you should put it like

  private void button2_Click(object sender, EventArgs e) {
    MyForm rr = new MyForm(); // <- MyForm not Form!
    rr.ShowDialog();
  }

Upvotes: 1

Related Questions