How to Get all Forms and Open Form with Form Name in C#

By FoxLearn 11/28/2024 2:30:23 PM   11.08K
In C#, you can dynamically open or call a form by its name at runtime using reflection or by managing a collection of form names and their associated instances.

In this article, we'll create a simple AppForm class to map data for various forms, and demonstrate how you can use this data to dynamically load and display forms from a ComboBox selection.

How to Dynamically Retrieve and Open Forms by Name in C#?

Open Viual Studio, then click 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

Next, Design your form as shown below.

dynamic call form c#

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

Create an AppForm to map data

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

The AppForm class will be a simple data model to store the form's identifier (Id) and name (FormName). This class is used to map the forms available in the application.

We'll create a Windows Forms application that allows users to select a form from a ComboBox, and then open the selected form dynamically at runtime.

Here's the implementation of the Form1 class.

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();
        }

        // Event handler to initialize the form when it's loaded
        private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize the list of AppForm objects
            List<AppForm> list = new List<AppForm>();
            // Get the base form type
            Type formType = typeof(Form);
            // Loop through all types in the current assembly
            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                // If the type is a form, add it to the list
                if (formType.IsAssignableFrom(t))
                    list.Add(new AppForm() { Id = t.FullName, FormName = t.Name });
            }
            // Initialize ComboBox with the list of AppForms
            cboFormName.DataSource = list;
            cboFormName.ValueMember = "Id";
            cboFormName.DisplayMember = "FormName";
        }

        // Event handler to open the selected form when the button is clicked
        private void btnOpen_Click(object sender, EventArgs e)
        {
            // Get the selected AppForm object
            AppForm obj = cboFormName.SelectedItem as AppForm;
            // If the object is valid, create and open the form dynamically
            if (obj != null)
            {
                Type t = Type.GetType(obj.Id);
                if (t != null)
                {
                    // Create a new instance of the selected form
                    Form frm = Activator.CreateInstance(t) as Form;
                    if (frm != null)
                        frm.ShowDialog();
                }
            }
        }
    }
}

We initialize a list of AppForm objects. Each object represents a form in the application with its Id and FormName.

Using Assembly.GetExecutingAssembly().GetTypes(), we loop through all types in the current assembly and check if they are subclasses of Form using formType.IsAssignableFrom(t).

We bind the list of AppForm objects to the ComboBox (cboFormName), setting the ValueMember to Id and the DisplayMember to FormName.

When the "Open" button is clicked (btnOpen_Click), we get the selected AppForm from the ComboBox, use Type.GetType() to get the corresponding Type object, and create a new instance of the selected form using Activator.CreateInstance().

VIDEO TUTORIAL