Adrian Brown
Adrian Brown

Reputation: 133

Check if tab exists in TabControl c#

I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

Upvotes: 0

Views: 5307

Answers (3)

This is a better way:

if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    VulnTab = new TabPage("Vulnerability");
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}

Upvotes: 0

Dominik Szymański
Dominik Szymański

Reputation: 822

Your problem is, that you are creating completely new page every time. As you are defining private TabPage object, you could move it to the class (Form?) scope and check if it's null, like in example below:

private TabPage VulnTab;

private void ButtonClicked(object sender, EventArgs args)
{
    if (VulnTab != null)
    {
        tabControl1.SelectedTab = VulnTab;
    }
    else
    {
        VulnTab = new TabPage("Vulnerability");
        tabControl1.TabPages.Add(VulnTab);

        tabControl1.SelectedTab = VulnTab;
        var vuln = new vulnerability();
        tabControl1.SelectedTab.Controls.Add(vuln);
    }
}

Of course ButtonClicked is just whatever method fires your action of creating and/or changing the tab.

For your future reference: If you create new object (by using keyword new) you are creating completely new object. They might be identical, but they are not the same thing, like two apples which look the same aren't the same apple. Only under some specific conditions (object being simple type (numbers, DateTime) or having IEquatable implemented) two objects created in two separate places might be equal to .NET.

Upvotes: 2

SLaks
SLaks

Reputation: 887225

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)

You just created a brand new TabPage. Obviously, that isn't in TabPages.

You need to check the existing instance, by only creating it once.

Upvotes: 2

Related Questions