I have come across this problem before and had the requirement that we use no third party controls so that the application could be easily handed over to a third party. To get around this we had a main form which we set IsMdiContainer = true
and dock a TabControl
to the to of the main form so that only the TabItem
s are visible and the contents is not.
Now, this is not the nicest, but it solves the problem and allows you to write the contents of each tab as a seperate form having its own class etc. On the main form set the load event to load the relevant forms into you TabControl
.
Note, you can replace the use of Form
s in what follows with UserControl
s but you will use the ability to have the main form as an MdiContainer and will have to use a Panel
to dock controls and add some code to bring each user control to front.
private void MainForm_Load(object sender, EventArgs e)
{
try {
LoadMdiForms();
}
finally {
mdiTabControl.SelectedIndex = 0;
}
}
Then set up a List<Form> MdiChildForms { get; set; }
and add you forms
private void LoadMdiForms()
{
createDbForm = new CreateDbForm();
MdiChildForms.Add(createDbForm);
valForm = new ValidationForm();
MdiChildForms.Add(valForm);
// et al.
foreach (Form mdiChild in MdiChildForms)
{
mdiChild.MdiParent = this;
mdiChild.ShowInTaskbar = false;
mdiChild.Show();
}
}
Now set up an MainForm_MdiChildActivate
event handler
private void MainForm_MdiChildActivate(object sender, EventArgs e)
{
if (this.ActiveMdiChild == null)
mdiTabControl.Visible = false; // If no child forms, hide tabControl
else
{
// Child form always maximized.
this.ActiveMdiChild.WindowState = FormWindowState.Maximized;
// If child form is new and has no tabPage, create new tabPage.
if (this.ActiveMdiChild.Tag == null)
{
// Add a tabPage to tabControl with child form caption
TabPage tp = new TabPage(this.ActiveMdiChild.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = mdiTabControl;
mdiTabControl.SelectedTab = tp;
this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
}
// Make visible if required.
if (!mdiTabControl.Visible)
mdiTabControl.Visible = true;
}
}
Now add the event handler on the TabControl
SelectedIndexChanged
event
// If child form closed, remove tabPage.
private void ActiveMdiChild_FormClosed(object sender, FormClosedEventArgs e)
{
((sender as Form).Tag as TabPage).Dispose();
}
private void mdiTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
if ((mdiTabControl.SelectedTab != null) &&
(mdiTabControl.SelectedTab.Tag != null))
{
this.BeginUpdate();
(mdiTabControl.SelectedTab.Tag as Form).Select();
this.EndUpdate();
}
}
That's it. You should have a working TabControl
with atomic TabItem
s.
I hope this helps.