Windows Forms: Get all Forms and Open Form with Form Name in C#
By FoxLearn 7/27/2017 7:36:24 PM 10.7K
Get all forms, dynamically open or call form with form name in c# at runtime
Step 1: 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
Step 2: Design your form as below
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
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#