Reputation: 2173
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?
Upvotes: 2
Views: 7280
Reputation: 2172
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.
Upvotes: 0
Reputation: 13741
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
Upvotes: 3