65.9K
CodeProject is changing. Read more.
Home

Form as Tab

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (3 votes)

Apr 19, 2012

CPOL
viewsIcon

29438

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.