Ivan
Ivan

Reputation: 5248

Winforms - How to create new tab and TabPage from current form to MainWindow form

I have a MainWindow form which contains TabControl component where dynamicly on click on menuItem I create a new tab and TabPage. The new created TabPage contains a new Form.

The new opened TabPage, which contains the new Form en.Products have DataGridView with products list. When I double click on a cell in the DataGridview from Products form I want to open new tabPage to Mainwindow.

enter image description here

dataGridView1_CellContentDoubleClick -> open new tab in main window

In MainWindow I create:

private void ProductListToolStripMenuItem_Click(object sender, EventArgs e)
{
    ProductForm = f = new Form();

    CreateTabPage(f);
}

private void CreateTabPage(Form form)
{
    form.TopLevel = false;

    TabPage tabPage = new TabPage();
    tabPage.Text = form.Text;
    tabPage.Controls.Add(form);

    mainWindowTabControl.Controls.Add(tabPage);
    mainWindowTabControl.SelectedTab = tabPage;

    form.Show();
}

From Product form I want to send data to MainWindow form to create new TabPage which is already defined in MainWindow.

public partial class Product: Form
{
   private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
         // create new tab page to MainWindow form
    }
}

I am not using MDI and I think this is impossible without creating a new MainWindow instance and pass parameters. In my case the MainWindow is already opened, if I close MainWindow all will be closed.

Any idea how to solve this issue?

Upvotes: 0

Views: 3835

Answers (1)

Sunil
Sunil

Reputation: 3424

Create a property on you MainWindow that exposes the mainWindowTabControl as a property

public System.Windows.Forms.TabControl MainTabControl
{
  get 
  {
     return mainWindowTabControl;
  }
}

Now, have a property on your Product form, MainFormRef, so when you create instance of your Product form, pass reference of your MainWindow to it:

Product p = new Product();
p.MainFormRef = this;

Now use this to add new tabs:

public partial class Product: Form
{
    public Form MainFormRef { get; set; }
    private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
         // create new tab page to MainWindow form
         TabPage tabPage = new TabPage();
         tabPage.Text = form.Text;
         tabPage.Controls.Add(form);

         MainFormRef.MainTabControl.Controls.Add(tabPage);
         MainFormRef.MainTabControl.SelectedTab = tabPage;
    }
}

Upvotes: 1

Related Questions