How do I use code to insert or delete tabpages in a TabControl

Platform: WinForms| Category: TabControl

To delete a tabpage, you use the tabControl1.Controls.Remove method. To add a new page as the last tab, use the tabControl1.Controls.Add method. Here is some sample code.

	//remove the selected tab
	tabControl1.Controls.Remove(tabControl1.SelectedTab);

	//add a new tabpage as the last tab
	tabControl1.Controls.Add(new TabPage('new Page'));

There does not appear to be support in the framework for inserting a tab at a particular position. A work around might be to save the current tabpage controls, clear the Controls collection, and then add the saved controls back to the Controls collection inserting a new tab. Here is some code that does this.

	private void InsertTab(int tabNumber, ref TabControl tabControl)
	{
		int limit = tabControl.Controls.Count;
		if(tabNumber < 0 || tabNumber > limit)
		{
			tabControl.Controls.Add(new TabPage('new Page'));
			return;
		}
		
		int target = tabControl.SelectedIndex;
			
		//save the existing pages & clear the controls
		Control [] c = new Control[limit];
		tabControl.Controls.CopyTo(c, 0);
		tabControl.Controls.Clear();

		//add the earlier pages
		for (int i = 0; i < target; ++i)
			tabControl.Controls.Add(c[i]);
		//insert the page
		tabControl.Controls.Add(new TabPage('new Page'));
			
		//add the later pages
		for (int i = target; i < limit; ++i)
			tabControl.Controls.Add(c[i]);

		//select the new page
		tabControl.SelectedIndex = target;
	}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.