I am trying to write a generic method which would allow me to add a form as the contents of a Tab on a tab control, however I am only able to figure out how to add it when specifying the exact form I wish to add.
Suppose I have three forms Form1
, Form2
, and Form3
where Form1
contains the tab control tabControl1
, and Form2
inherits Form
, where Form3
inherits MetroForm
. Following is the method I am currently using :
private void AddFormAsTab() {
Form3 f = new Form3()
{
TopLevel = false,
ShowInTaskbar = false,
ControlBox = false,
SizeGripStyle = SizeGripStyle.Hide,
Visible = false,
Text = string.Empty,
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill,
MinimizeBox = false,
MaximizeBox = false,
ShadowType = MetroFormShadowType.None,
Movable = false
};
TabPage tab = new TabPage();
tab.Controls.Add( f );
tabControl1.TabPages.Add( tab );
f.Visible = true;
}
What I would like to do, is modify this method so that AddFormAsTab()
accepts any form type and sets the properties as necessary (to ensure they are set as I am lazy and do not wish to change all those properties on every form I design perpetually when recycling this component)
I have seen this done in other controls such as Telerik, and DevExpress where the control accepts a generic and modifies it to 'fit' the purpose. In my case, I am changing the properties of the form so that it fills the tabpage, has no border, title bar, etc.
I have considered using (typeof(T))obj
type code, but this generates pre-compile errors where those properties do not exist in obj
which prevent it from being built, even though in theory, this should work.
I have also tried stuff like Form f = new Form1()
, however this doesn't work as Form
is not the same type as Form1
which happens to inherit Form
.
What can I do to make this happen, to allow any form to be set without hardcoding those specific forms classes into the AddFormAsTab()
method, but still delegate responsibility to set the required properties to that method ?
Ideally, something like :
private void AddFormAsTab<T>(T obj) { ... }