SoFunction
Updated on 2025-03-07

C# Share the method of opening the corresponding form through reflection

C# The method of opening a form by reflection when clicking a menu bar or toolbar can replace the long if-else or switch-case statement. Important: Set the name of the menu or toolbar item to the same name as the corresponding form (key).

private void MenuItem_Click(object sender, EventArgs e)
{
   ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
   Form form = (Form)(“Your assembly name”).CreateInstance(“Form namespace. “+ ); //Note: You must add a dot after the namespace    = this; //If it is an Mdi form, please add this line   ();
}

If one of our forms has N forms, or if there is a Tree that needs to call N forms correspondingly, it may be very troublesome to use the IF ELse method.

I might write this way.

private void button3_Click(object sender, EventArgs e)
    {
      //Get the clicked Button name      string btnname = ((Button)sender).Name;
      if (btnname == "button1")
      {
        //Processing the form      }
      else if (btnname == "button2")
      {
        //Processing the form      }
      else
      {
        //Processing the form      }
    }

This is not impossible, but if there are more than 100 or more, it will not work.
It can be said that more than 10 are not fun, but it is very convenient to use reflection, and only a few lines of code is enough.
Look at the following method

/// <summary> 
    /// Open a new subform    /// </summary> 
    /// <param name="strName">The class name of the form</param>    /// <param name="AssemblyName">The name of the class library where the form is located</param>    public static void CreateForm(string strName, string AssemblyName)
    {
      string path = AssemblyName;//The Assembly option name of the project      string name = strName; //The name of the class      Form doc = (Form)(path).CreateInstance(name);
      ();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //Get the clicked Button name      string btnname = ((Button)sender).Text;
      CreateForm("WindowsFormsApplication1." + btnname, "WindowsFormsApplication1");
    }

With the above method, as long as our user control Text is the same as the class name of the form, it can be dynamically loaded. Of course, if some comrades say that my Text needs to be used in Chinese characters, then change the attribute, such as Name or other attributes. In short, it will definitely be much more convenient than writing one by one.

The above is the entire content of this article, I hope you like it.