Opening and Closing Tab Pages via Checkbox

…衆ロ難τιáo~ 提交于 2019-12-11 14:10:08

问题


I am working on Windows Forms app using C#. The main form contains TabControl and checkboxes. The tab pages of the TabControl contains child forms. Then the checkboxes shall open and close specific tab pages on check and uncheck, respectively. The tab pages initially do not exist on load.

Here is what I did (child form is Form3 and the concerned TabControl is tabForms):

private void checkBox1_CheckStateChanged(object sender, EventArgs e)
    {

        Form1 f1 = new Form1();
        f1.TopLevel = false;
        TabPage tp1 = new TabPage(f1.Text);


        if (checkBox1.Checked == true)
        {
            tabForms.TabPages.Add(tp1);
            tp1.Show();
            f1.Parent = tp1;
            f1.Show();
        }
        else
        {
            tp1.Hide();
            tabForms.TabPages.Remove(tp1);
            f1.Dispose();
        }
    }

With this code, opening the tab was not a problem. However, when I unchecked checkBox1, the tab page won't close and when I checked it again, it opened another of the same tab page.

What did I miss or what shall I do to rectify this (if my aim was possible that is)?


回答1:


Your code creates a brand new TabPage control instance whenever the CheckBox state changes. This is fine as long as you have to add a TabPage, but not when you are attempting to remove an existing tab.

In the second case, you try to remove a new TabPage instance from the pool of pages contained within the TabControl. This obviously produces nothing, since the new has never been added to the TabControl:

TabPage tp1 = new TabPage(f1.Text);
tabForms.TabPages.Remove(tp1); //  instance not found, nothing is removed

Use the following approach instead, which hides the existing TabPage and then reuses it as needed:

private TabPage m_MyTabPage = new TabPage();

private void checkBox1_CheckStateChanged(object sender, EventArgs e)
{
    Form1 f1 = new Form1();
    f1.TopLevel = false;

    if (checkBox1.Checked)
    {
        m_MyTabPage.Text = f1.Text;
        tabForms.TabPages.Add(m_MyTabPage);

        tp1.Show();
        f1.Parent = tp1;
        f1.Show();
    }
    else
    {
        tp1.Hide();
        tabForms.TabPages.Remove(m_MyTabPage);
        f1.Dispose();
    }
}


来源:https://stackoverflow.com/questions/48052105/opening-and-closing-tab-pages-via-checkbox

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