简体   繁体   中英

TabPage keeps being created. C#

TabPage keeps being created even the tab page already exists in my tab control. 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. Try looping through the tab pages and comparing the Name property instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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