Home > Back-end >  Proper instatiating a WinForm via string in C#
Proper instatiating a WinForm via string in C#

Time:04-10

I am working on a Winforms application that uses base window (e.g. Form1) and many other windows (e.g. Form2, Form3, ...). All of these windows have their property TopLevel set to false, no border and I am placing them in the Form1 when I need them. I am not skilled enough or do not have the brain capacity to solve this issue:

public void ShowForm(string strNewForm) {
   var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;

   frmNew.TopLevel = false;
   frmNew.Size = new Size(rctForm.Width, rctForm.Height);
   frmNew.Location = new Point(rctForm.X, rctForm.Y);
   frmNew.InitializeForm(strActualSection, strActualSubSection);
   frmNew.Parent = this;

   frmNew.Show();  
}

The strNewForm variable contains the name of Form to show. All the methods and properties in each Form can be used as these all are inherited from base class Form. Problem is with InitializeForm() which I use in each form (Form2, Form3, ...) to do various stuff. I know my problem is in this line:

var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;

When strNewForm contains string "Form2" and I change as Form to as Form2 it works just fine. I know I need to change it to proper name each time, but I don't know how. I tried to use this:

Type frmType = Type.GetType(strNewForm);
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as frmType;

But it throws an error CS0118: frmType is a variable but is used as a type. I don't know how to solve this, I tried many solutions and I googled for half a day straight and I am still lost. Any insight would be really helpful.

CodePudding user response:

You cannot use a run-time variable to create strongly-typed code.

You have to provide a compile-time type after the as.

If you know it's a Form then all you can do is this:

var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;

If you need specific methods or properties then use a custom Form as your base-type and use that in the as.

CodePudding user response:

Why won't you pass a Form object in your ShowForm method?

public void ShowForm(Form newForm) 
{
   newForm.TopLevel = false;
   newForm.Size = new Size(rctForm.Width, rctForm.Height);
   newForm.Location = new Point(rctForm.X, rctForm.Y);
   newForm.InitializeForm(strActualSection, strActualSubSection);
   newForm.Parent = this;

   newForm.ShowDialog();  
}
  • Related