I'm building a small tabbed c# Form and I'd like each tab page to have some common features, notably, an OK button and an error message and to have a space for the specific form fields.
Has anyone else done something similar and how did you approach it?
To create a TabControl control at design-time, you simply drag and drop a TabControl control from Toolbox onto a Form in Visual Studio. After you drag and drop a TabControl on a Form, the TabControl1 is added to the Form and looks like Figure 1. A TabControl is just a container and has no value without tab pages.
Right-click on the tab control and select properties. You can see the tab page called "Collection Editor". To add an additional tab, please click the add button. To remove a tab, select it and click remove.
This is easy to do without extending either TabControl/TabPage.
Define one UserControl, and put the common elements on it you want on every TabPage.
On the Form: go ahead and design the TabPage specific controls you want for each TabPage : make sure they are not going to visually overlap with the common controls once the UserControl has been added.
In the Form Load Event of your main Form do something like this :
// form scoped variable to hold a referece to the current UserControl
private UserControl1 currentUserControl;
private void Form1_Load(object sender, EventArgs e)
{
foreach(TabPage theTabPage in tabControl1.TabPages)
{
currentUserControl = new UserControl1();
theTabPage.Margin = new Padding(0);
theTabPage.Padding = new Padding(0);
theTabPage.Controls.Add(currentUserControl);
currentUserControl.Location = new Point(0,0);
currentUserControl.Dock = DockStyle.Fill;
currentUserControl.SendToBack();
}
}
Even though the 'SendToBack isn't really required here it is "insurance" that your UserControl with the 'Okay button and TextBox for an error message are placed behind the individual controls you have assigned to each TabPage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With