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



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SLaks
Solution 2 Nandostyle