简体   繁体   English

TabPage不断创建。 C#

[英]TabPage keeps being created. C#

TabPage keeps being created even the tab page already exists in my tab control. 即使标签页已经存在于我的标签控件中,TabPage仍会继续创建。 Please consider my code below: 请考虑以下我的代码:

void button1_Click(object sender, EventArgs e)
{
    TabPage tabPage = new TabPage();
    tabPage.Name = "TestNewTab";
    tabPage.Text = "Tab Page";

    // Check if the tabpage is not yet existing
    if (!tabControl1.TabPages.Contains(tabPage))
    {
        // Add the new tab page
        tabControl1.TabPages.Add(tabPage);
    }
}

What's wrong with my code? 我的代码有什么问题? Thanks. 谢谢。

My guess would be that TabPages.Contains is checking for an object reference, since you're instantiating a new TabPage every time, it won't be the same object. 我的猜测是TabPages.Contains正在检查对象引用,因为每次都实例化一个新的TabPage时,它将不会是同一对象。 Try looping through the tab pages and comparing the Name property instead. 尝试遍历选项卡页面并比较Name属性。

The problem is that .Contains will check for an equal reference, which is not the same as an equal value, when looking for a reference type like TabPage . 问题是.Contains在查找类似TabPage的引用类型时会检查是否等于引用,而不是等于相等的值。 A simple way to fix your problem might be to do something like this: 解决问题的一种简单方法是执行以下操作:

TabPage tabPage;

void button1_Click(object sender, EventArgs e)
{
    // Check if the tabpage doesn't exist yet:
    if (tabPage == null)
    {
        // Create the tab page:
        tabPage = new TabPage();
        tabPage.Name = "TestNewTab";
        tabPage.Text = "Tab Page";

        // Add the new tab page:
        tabControl1.TabPages.Add(tabPage);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM