2

I have a tab control in a form and user controls are loaded onto each tab page at the form load event. I want to switch between tabs using command buttons within the tab pages, meaning the buttons are in different user controls and not on the form.

tabControl1.SelectedTab = tabPage2;

could not be used because of that. How can I achieve this?

Lizzy
  • 2,033
  • 3
  • 20
  • 33

2 Answers2

3
tabControl1.SelectedIndex = index; 
//where index is the index (integer value) of the tabpage you want to select

UPDATE

Check: How to access properties of a usercontrol in C#

Expose the properties as properties of your user control like this:

public int TabControlIndex
{
get { return tabControl1.index; }
set { tabControl1.index = value; }
 }

you can call the same on your form load event like this:

Usercontrol1.TabControlIndex = index;
//where index is the index (integer value) of the tabpage you want to select
Community
  • 1
  • 1
reggie
  • 13,313
  • 13
  • 41
  • 57
  • I can't access the tabControl from the user control as it is on the form, not on the user control. The user controls are loaded onto the tab pages and the buttons are also on these user controls. – Lizzy Aug 30 '11 at 15:57
  • Please check the update. I have provided a link in my answer above.Also added a piece of code based on the solution mentioned in the link. Let me know if that helps. – reggie Aug 30 '11 at 16:10
0

You can pass TabControl instance (along with its pageIndex) to your UserControl as a parameter either via constructor or some initializer method:

MyUserControl userControl = new MyUserControl(tabControl1, pageIndex1);

or

MyUserControl userControl2 = new MyUserControl();
userControl2.BindToTabControl(tabControl1, pageIndex2);

In this case your UserControl will be able to handle user clicks and switch tabs.

Or you can create events in your UserControl that will fire when user clicks on UserControl's button. Your main form should subscribe to this events and handle them. In this case the code of your main form will be responsible for switching tabs. It's a better solution I think.

Artemix
  • 2,113
  • 2
  • 23
  • 34