通过复选框打开和关闭标签页 [英] Opening and Closing Tab Pages via Checkbox

查看:44
本文介绍了通过复选框打开和关闭标签页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# 开发 Windows 窗体应用程序.主窗体包含 TabControl 和复选框.TabControl 的标签页包含子窗体.然后复选框将分别在选中和取消选中时打开和关闭特定的标签页.标签页最初在加载时不存在.

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.

这是我所做的(子表单是 Form3,相关的 TabControl 是 tabForms):

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

使用此代码,打开选项卡不是问题.但是,当我取消选中 checkBox1 时,标签页不会关闭,当我再次选中它时,它打开了另一个相同的标签页.

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)?

推荐答案

每当 CheckBox 状态发生变化时,您的代码都会创建一个全新的 TabPage 控件实例.只要您必须添加 TabPage,这就没问题,但当您尝试删除现有选项卡时则不然.

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.

在第二种情况下,您尝试从 TabControl 中包含的页面池中删除一个新的 TabPage 实例.这显然不会产生任何结果,因为新的从未被添加到 TabControl:

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

改用以下方法,隐藏现有的TabPage,然后根据需要重用它:

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

这篇关于通过复选框打开和关闭标签页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆