'How to create a form named button in C # and display the form by pressing it

I wrote a program in which I can create a shortcut from the side forms to the main form. But when I click on each button, the relevant form does not open.

Why?

Because the amount of type to be sent is sent as null.

I will send you the relevant code. Can you help me solve the problem?

public void CreatShortCut(string idForm, string nameForm)
    {
        if (string.IsNullOrWhiteSpace(nameForm))
        {
            return;
        }
        else
        {
            button = 
                new System.Windows.Forms.Button();

            button.Name = $"{idForm}Button";
            button.Text = nameForm;
            button.Size = new System.Drawing.Size(100, 30);
            button.TabIndex = 0;
            button.UseVisualStyleBackColor = true;
            button.ContextMenuStrip = contextMenuStrip;
            button.Click += Button_Click;
            button.MouseEnter += Button_MouseEnter;
            
            shortcutPanel.Controls.Add(button);             
        }
    }


private void Button_Click(object sender, System.EventArgs e)
    {
        try
        {
            System.Windows.Forms.Button button = sender as System.Windows.Forms.Button;

            string typeName = 
                button.Name.Replace("Button", string.Empty).Trim();

            var form = 
                (System.Windows.Forms.Form)System.Activator.CreateInstance(System.Type.GetType(GetType().Name + "." + typeName));

            form.ShowDialog();
        }
        catch (System.Exception ex)
        {
            System.Windows.Forms.MessageBox.Show($"{ex.Message}");
        }
    }


Solution 1:[1]

You're better off not passing around strings and you should avoid activators. Instead you should use generics.

Try this:

public void CreatShortCut<F>(string nameForm) where F : Form, new()
{
    if (string.IsNullOrWhiteSpace(nameForm))
    {
        return;
    }
    else
    {
        var button = new System.Windows.Forms.Button();
        button.Text = nameForm;
        button.Size = new System.Drawing.Size(100, 30);
        button.TabIndex = 0;
        button.UseVisualStyleBackColor = true;
        button.ContextMenuStrip = contextMenuStrip;
        button.Click += (s, e) =>
        {
            var form = new F();
            form.ShowDialog();
        }
        shortcutPanel.Controls.Add(button);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Enigmativity