Windows Forms: Get all Forms and Open Form with Form Name in C#

By FoxLearn 7/27/2017 7:36:24 PM   10.91K
Get all forms, dynamically open or call form with form name in c# at runtime

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DynamicOpenForm" and then click OK

dynamic open form c#Step 2: Design your form as below

dynamic call form c#

You can create an empty Form2, Form3, Form4 to play demo

Step 3: Create an AppForm to map data

public class AppForm
{
    public string Id { get; set; }
    public string FormName { get; set; }
}

Step 4: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DynamicOpenForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Init Form
            List<AppForm> list = new List<AppForm>();
            Type formType = typeof(Form);
            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (formType.IsAssignableFrom(t))
                    list.Add(new AppForm() { Id = t.FullName, FormName = t.Name });
            }
            //Init combobox
            cboFormName.DataSource = list;
            cboFormName.ValueMember = "Id";
            cboFormName.DisplayMember = "FormName";
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            AppForm obj = cboFormName.SelectedItem as AppForm;
            if (obj != null)
            {
                Type t = Type.GetType(obj.Id);
                if (t != null)
                {
                    //Create a new instance
                    Form frm = Activator.CreateInstance(t) as Form;
                    if (frm != null)
                        frm.ShowDialog();
                }
            }
        }
    }
}

VIDEO TUTORIALS