Home > OS >  how to disable duplicate open of same childform in a tab control
how to disable duplicate open of same childform in a tab control

Time:04-03

what i want to happen is when i open the specific form in a tab control it will show and when i accidentally click the button of that specic form is it will automatically focused on that form and to avoid open it again in another tab page.

Here is my method:

private void CreateTabPage(Form form)
{ 
form.TopLevel=false;
TabPage tabPage = new TabPage();
tabPage.Text = form.Text;
tabPage.Controls.Add(form);
form.Dock = DockStyle.Fill;

currenttab = form;
tabPage.Tag = form;
tabControl1.Controls.Add(tabPage);
tabControl1.SelectedTab = tabPage;
form.Show();

}`

and here is my code in a button eventhandler code:

CreateTabPage(new Form1());

CodePudding user response:

The problem is that you're calling new Form1(), which creates a new instance of the form each time it's called. Instead, you need to hold a reference to the existing instance of Form1, and show that instance, for example:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            var form2 = new Form2(this);
            form2.Show();
        }
    }

    public partial class Form2 : Form
    {
        private readonly Form1 form1;

        public Form2(Form1 form1)
        {
            InitializeComponent();
            this.form1 = form1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.form1.Activate();
        }
    }

CodePudding user response:

You can iterate over the existing TabPages and see if one of them already has the same type of the form being requested:

private void CreateTabPage(Form form)
{
    foreach(TabPage tp in tabControl1.TabPages)
    {
        if(tp.Controls.Count>0 && tp.Controls[0].GetType().Equals(form.GetType())) {
            tabControl1.SelectedTab = tp;
            return;
        }
    }

    form.TopLevel = false;
    TabPage tabPage = new TabPage();
    tabPage.Text = form.Text;
    tabPage.Controls.Add(form);
    form.Dock = DockStyle.Fill;

    currenttab = form;
    tabPage.Tag = form;
    tabControl1.Controls.Add(tabPage);
    tabControl1.SelectedTab = tabPage;
    form.Show();
}
  • Related