Monday, February 5, 2007

Creating a new form at runtime....

Hi all,

Yesterday while supporting user @ Experts-Exchange, I came across a question asking if I could create an instance of a new FORM at runtime and show it on the screen.

Well thinking at the first instance, looks quite straight forward. Theoritically its like creating a new instance of an object and using its methods and properties.

But practically its not as easy as with any other object. Theoritically the below code shows what exactly he wanted and its exactly what we can do in general coding with any other objects.

String strFormName = "Form1";
Form frmNew = (Form)(strFormName); //A new form with the name "Form1"
frmNew.Show();

So exploring through for the same at first hit it looked impossible and thats what I thought.
But then I was guided to an article on MSDN that explained using Activator.CreateInstance For all such tasks and it looked quite obvious.

Here's the code for it.

String strFormName = "Form1";
System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
Form frmNew = (Form)asm.CreateInstance(asm.Getname.name + "." + strFormname, true);
frmNew.Show();

Hope someday this would be of use to me as well ;-)

--Ashutosh


No comments:

Post a Comment