Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data type (string) to type (form)

Tags:

c#

winforms

I have a form name stored in a string variable, and i want to pass this string to class which take Form Type

string Str = "MainForm";       // this is form name 
// I try to convert the data type string to form type like this
Form FormNm = (Form) Str ;
// there is the message appears cannot convert type 'sting'   to 'form'
TransLang.SaveControlsLanguage(FormNm);   // this is the class

Thank you

like image 754
Sherif Sanad Avatar asked Dec 15 '25 06:12

Sherif Sanad


2 Answers

string myType = "MyAssembly.MyType";

Assembly asm = Assembly.LoadFrom("MyAssembly.dll"); // creating instance by loading from other assembly
//Assembly asm = Assembly.GetExecutingAssembly();  // for creating instance from same assembly
//Assembly asm = Assembly.GetEntryAssembly(); // for creating instance from entry assembly
Type t = asm.GetType(myType);

Object obj = Activator.CreateInstance(t, null, null);

since it is a System.Windows.Form if u want to show the form u can do like

Form frm = obj as Form; // safely typecast
if (frm != null) // kewl it is of type Form
{
    //work with your form
    fmr.Show();
}
like image 78
Parimal Raj Avatar answered Dec 16 '25 22:12

Parimal Raj


System.Reflection.Assembly.GetExecutingAssembly();
  Form frm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
  frm.Show();

add this to your code.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!