'Implement form parts in different classes
I have a main window with two buttons (this is a simplified description). A click on a button opens another form. Both buttons open different forms.
I'd like to move the content of the two sub forms to the main window and switch between them using a TabControl
, but I don't want to move the complete code to the main window class.
How can I keep the code separated? One idea I had is to create two user controls, instead of the two sub forms. Are there other/better options?
Solution 1:[1]
If you want to move the sub-forms initially, before the user may change the values of their components, you could as well put that functionality into the partial class
the rest of the main-form (in this example Form1
) is in, just with yet another file. More on partial classes
Otherwise, you could do something like this:
public Form1() {
InitializeComponent();
SubForm1 sub1 = new SubForm1();
this.tabPage1.Controls.Add(sub1.button1);
this.tabPage1.Controls.Add(sub1.button2);
SubForm2 sub2 = new SubForm2();
this.tabPage2.Controls.Add(sub2.label1);
this.tabPage2.Controls.Add(sub2.checkBox1);
}
You will have to make sure every control in the sub-forms is public
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |