'how to disable duplicate open of same childform in a tab control
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());
Solution 1:[1]
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();
}
}
Solution 2:[2]
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();
}
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 | sbridewell |
| Solution 2 | Idle_Mind |
