Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Form as Tab

0.00/5 (No votes)
19 Apr 2012 1  
Easy way to Open Form as Tab in c#.Net

Introduction

I have done some projects in .NET and this is my first article.

I searched for solution to use WinForms as Tabs, but the solutions were too high level. My style is I find solution, try to understand the code, and write my own what I so that can understand and will remember better same for the next time. But unfortuntely, the solutions I found were so high level I couldn't decipher the code.

Background

Today I was trying to find how to add one WinForm to another as

private void btnOpneForm_Click(object sender, EventArgs e)
{             
  Form childForm = new Form();
  childForm.Parent = this;
  childForm.WindowState = FormWindowState.Maximized;
  childForm.Show(); 
}

Running this code gives error "top-level control can not be added to control" I searched and found the solution; it is simple. All I have to do is set the TopLevel property of childForm to false. And it worked! Now, this gives me an Idea ('',)...

Using the Code

I have added tabControl1 to the parent form, created new TabPage and added this form to TabPage.

Code is like:

//
// stophereareyou@gmail.com
// 
        Form childForm = new Form();
        public Form2()
        {
            InitializeComponent();
            childForm.FormClosing += new FormClosingEventHandler(childForm_FormClosing);
        }

        void childForm_FormClosing(object sender, FormClosingEventArgs e)
        {
//Close Parent Tab
            childForm.Parent.Dispose();
        }
  
        private void btnOpneForm_Click(object sender, EventArgs e)
        {
            //TopLevel for form is set to false
            childForm.TopLevel = false;
            //Added new TabPage
            TabPage tbp =new TabPage();
            tabControl1.TabPages.Add(tbp);
            tbp.Controls.Add(childForm);
            //Added form to tabpage
            childForm.WindowState = FormWindowState.Maximized;
            childForm.Show();
        }

Clicking the button btnOpneForm opens childForm in TabPage tbp.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here