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

戏子无情 提交于 2020-01-17 10:02:10

问题


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.

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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/48208918/winforms-how-to-create-new-tab-and-tabpage-from-current-form-to-mainwindow-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!