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

I have a form name stored in a string variable and I want to pass this string to a class that takes a 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

+3


source to share


5 answers


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

      



add this to your code.

+1


source


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 System.Windows.Form if u want to show u form can be done like



Form frm = obj as Form; // safely typecast
if (frm != null) // kewl it is of type Form
{
    //work with your form
    fmr.Show();
}

      

+2


source


you cannot directly convert string

to form

. you have to create a new form and set the form name to the appropriate line.

0


source


Well, you can't basically. What you can do is define a custom casting operator that, based on some logic given by a given string, creates a form. But that would be a pretty wired solution.

Instead, just redesign your code and build the form based on the provided string. For example:

//Dictionary of the string versus Forms
Dictionary<string,Form> data = new Dictionary<string,Form> {
   { "string1", new Form1()}, //different form type are associated
   { "string2", new Form2()}  // to different string keys
    .....
}; 

public Form GetForm(string value){    
   return data [value];
}

      

Just an idea, an architect, what you need.

0


source


You can use this code,

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

      

0


source







All Articles