Dynamic Forms in C#

Download DynamicForm.zip (18 KB)

Seasons greetings and happy new year! I thought it was about time for an update. Todays post is a control I’m developing for creating simple forms dynamically.

A form created dynamically from an object

I found myself creating lots of forms to edit simple objects, which required a lot of copy & pasting. What I wanted was to create a form dynamically using nothing but the object I wanted to change. There are frameworks already out there such as the DevExpress eXpressApp Framework (XPF), but I wanted something simple, light-weight and besides which I couldn’t resist the challenge.

The solution needed to be flexible enough to actually be useful, so I’ve decided to use custom attributes to control aspects of the form. This version uses 2 attributes:

string Label – Used to customize the control’s label
bool ReadOnly – Marks the control as disabled
bool Visible – Removes the control from the form
int Width – Sets the absolute width of the control

float MinValue – The minimum spinner value
float MaxValue – The maximum spinner value
int DecimalPlaces – The number of decimal place

The control inherits from Form, so can be used in the same way as a regular form. I’ve modified the constructor to accept a title, and an instance of the object to use. The same object can be read back from the DataItem property. The examples below show the general idea:

// using CodeOverload.Windows
public Example()
  DynamicForm df = new DynamicForm("Find", new Find());
  result = df.ShowDialog();
  if (result == DialogResult.OK)
    Find data = (Find)df.DataItem;
    // The data object is automatically bound to the form

Example 1:

public class Find
  public int TaskNumber { get; set; }

The class above would produce the following form:

Example 2:

public class Person
  public enum JobRole {Manager, Engineer}

  [DisplaySettings(Width = 200)]
  public string FirstName { get; set; }
  [DisplaySettings(Width = 200)]
  public string LastName { get; set; }

  public DateTime DateOfBirth { get; set; }
  public JobRole Role { get; set; }

The class above would produce the following form:

In the next few weeks I’ll see if I can add some validation. Full source code is available:

Download DynamicForm.zip (18 KB)

This entry was posted in Projects and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s