Winforms, create form instance by form name

前端 未结 2 606
后悔当初
后悔当初 2020-12-19 21:51

I need a method that returns a new instance of a form by the name of the form. Here is what I have so far:

    public Form GetFormByName(string frmname)
             


        
相关标签:
2条回答
  • 2020-12-19 22:33

    You need the Activator.CreateInstance method which creates an instance of a type given a Type:

    public Form TryGetFormByName(string frmname)
    {
        var formType = Assembly.GetExecutingAssembly().GetTypes()
            .Where(a => a.BaseType == typeof(Form) && a.Name == frmname)
            .FirstOrDefault();
    
        if (formType == null) // If there is no form with the given frmname
            return null;
    
        return (Form)Activator.CreateInstance(formType);
    }
    
    0 讨论(0)
  • 2020-12-19 22:45
    Assembly asm = typeof(EnterHereTypeInTheSameAssembly).Assembly;
    Type type = asm.GetType(name);
    Form form = (Form)Activator.CreateInstance(type);
    
    0 讨论(0)
提交回复
热议问题