Windows Form Design at Run Time

Introduction

Doing Windows Forms design at runtime will allow users to design the form at runtime, save the form then open and reuse the existing form. The user can add controls at runtime from the Toolbar, design their form and write the code for controls to do some action. Now for example a user can add a DataGridView and a Button Control at runtime. In the code part for a Text Box the user can add their code to bind data from a database to the selected Data Grid. Everything can be done at runtime.

Windows Form Design

This Windows Forms design at runtime will be useful for:

  1. Project Manager/System Analyst where they can design a new project and hand it over to a developer programmer and software engineer.

  2. Will be useful for Project Demo to a client. In some case clients need ad hoc form design and sample output of form looks. In that case this application will be very useful to design their form and show it for demo purposes with less time.

  3. Teaching and training of new programmers, developers, trainers and teachers for explaining the basic Windows Forms controls, the properties of each control and how to write simple code for new programmers.
This Windows Forms design at runtime software application was developed to design your own form using a panel control and to add Labels, Buttons, TextBoxes, ListBoxes, DataGridViews, ListViews, CheckBoxes and so on. The user can add/change the background color/image of the form (here we used a Panel). The user can add items to ComboBoxes, TreeViews, ListViews and TextBoxes using the Properties Window. The user can enter their own C# code for a TextBox at a button to run their code at runtime, For example, add a button and in the TextBox add your code and click the button to see the runtime Button Click event. Here in this program, I have added a simple MessageBox display when clicking the Button. I have a plan to extend this function to bind data from XML and/or a database DataGridView. Using this application the user can bind data from a DataTable, XML file and from a SQL Data Source. This simple C# application allows the user to add:
  1. Create New Form.

  2. Save the Form as XML file.

  3. Open the Form from a XML file.

  4. Cut, Copy and Paste all controls.

  5. Delete all controls.

  6. Delete a selected control.

  7. Add/change a background color for the form (here a panel is used as the form).

  8. Add/Change BackGround Image for the Form.

  9. Add a Label Control and use the Property window to design your Label.

  10. Add a Button Control and use the Property window to design your Button.

  11. Add a CheckBox Control and use the Property window to design your CheckBox.

  12. Add a Button Control and use the Property window to design your Button.

  13. Add a ComboBox Control and use the Property window to design your ComboBox.

  14. Add a DataGridView Control and use the Property window to design your DataGridView.

  15. Add a DataTimePicker Control and use the Property window to design your DataTimePicker.

  16. Add a ListBox Control and use the Property window to design your ListBox.

  17. Add a ListView Control and use the Property window to design your ListView.

  18. Add a NumericUpDown Control and use the Property window to design your NumericUpDown.

  19. Add a PictureBox Control and use the Property window to design your PictureBox.

  20. Add a RadioButton Control and use the Property window to design your RadioButton.

  21. Add a TextBox Control and use the Property window to design your TextBox.

  22. Add a TreeView Control and use the Property window to design your TreeView.

  23. Bind data from a DataTable to return to a DataGridView, ListView, ComboBox and ListBox.

  24. Bind data from a XML file as a DataTable to return to a DataGridView, ListView, ComboBox and ListBox.

  25. Bind data from a SQL Server Database as a DataTable to return to a DataGridView, ListView, ComboBox and ListBox.

Application LayOut

In this application we can see a Toolbar at the left to add controls to the form (here our Panel). The center has a form (Panel) where the user can add and design their controls. In the right is a Property window to add all the design to the selected controls. In the bottom is a TextBox for the Code Part where the user can write their own code for runtime generated Button Click events.

Toolbar: Here we can see all the list of controls that can be added to the form at runtime. New Features have been added in Version 1.2. New features like Create New Form, Save Form, Open Form, Cut, Copy and Paste Controls.

Toolbar

Form (as Panel): Here we can see the Form (Panel) in the center where the user can add their controls and we can see the Message Box after a Button Click.

Form

Property Window: In the right we have the Property window useful for the user to do the design of their controls.

Property Window

Code part: At the bottom we can see the code part where the user can writer their own code. It has two part, the first panel contains "Select Control To Bind" ComboBox. Whenever the user adds a control to the Form(Panel) the control names will be added to this Combo Box. Here we can see now "grid_20" that is the name of the DataGridView that has been added to the form.

In "Code Type" the user can select the Button Click event type as "MessageBox", "Dat Tablereturn", "XML Data table Return, "SQL Database to Data Table return". And next we have a text box where the user can enter their code. Here below you can see a code to create a Data Table and add rows with data to the Data Table and finally return the Data Table.

Code Type

Here we can the “Select Control To Bind" ComboBox. Here we can see a list of controls that have been added to our form as a Grid, Label, Button, ListView and and so on. I have used control names with control type prefix 3 char and a random number.

Select Control To Bind
Message Box: Here we can see a sample of how to display a Message Box at runtime from a Button Click.

Message Box

Bind Controls from DataTable and XML File: Here we can see controls like, Label, ListBox, ComboBox, DataGridView, ListView and Button have been added. We should be carefull when selecting the controls that need to be bound and we can select our function type as "Dat Table return".

Note: Only in Button Click we can bind the Controls. So select your control to bound, for example Combo Box or ListBox or as you wish. Then in the text box enter your code to return the Datatable that can be bound to your selected control.

Bind Controls from DataTable

Here is the list of sample code that will be used to bind the data to the selected control. Just copy this code and paste it into the TextBox of the code part:

  1. Copy Code  
  2. //--for  return Datatable to Combobox/ListBox  
  3. DataTable dt = new DataTable();   
  4. dt.Columns.Add("itemCode");   
  5. dt.Columns.Add("ItemName");   
  6. DataRow row = dt.NewRow();  
  7.  row["itemCode"] = "0001";   
  8. row["ItemName"] = "SHANU";  
  9.  dt.Rows.Add(row);    
  10. row = dt.NewRow();  
  11.  row["itemCode"] = "0002";  
  12.  row["ItemName"] = "Afraz";   
  13. dt.Rows.Add(row);    
  14. row = dt.NewRow();   
  15. row["itemCode"] = "0003";  
  16.  row["ItemName"] = "Afreen";  
  17.  dt.Rows.Add(row);   
  18. return dt;  
  19. Copy Code  
  20. //-----------------  For  return Datatable to from XML FIle  
  21. //You can find the "ShanuDataSource.xml" XML file at my bin folder of Zip file.  
  22. //If you want to load your XML File Place it in the same Bin Folder.  
  23.   DataSet dataSet = new DataSet();  
  24.  dataSet.ReadXml("ShanuDataSource.xml");   
  25.  return dataSet.Tables[0];  
  26. Copy Code  
  27. // -----------------  From SQL SERVER Data Base to Data Table.  
  28.  string constring = @"Data Source=YourServerName;Initial Catalog=YourDBName;User id = sa;password=YourPWD";  
  29.             SqlConnection con = new SqlConnection(constring);  
  30.        SqlCommand cmd = new SqlCommand("select * from ItemMasters", con);  
  31.             cmd.CommandType = CommandType.Text;  
  32.                SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  33.                DataTable dt = new DataTable();                     
  34.                         sda.Fill(dt);  
  35.                          return dt; 

Bind Controls from SQL Server Database: Here we can see a sample of how to bind a SQL Server Database table data as the return of the Data Table to a DataGridView at runtime from a button click.

Bind Controls from

Using the code

The main code part in this application is to add controls at runtime and create an event like Mouse Enter, Mouse Leave, Resize Control, Mouse Move, Mouse Down and to create a class at runtime and to compile the code at runtime. All the code part has been well-commented so the user can easily understand the code.

Form Background: Here I used the Panel control to work as the form. I used the ColorDialog and OpenFileDialog to change the BackColor and Backgrond Image of the form (Panel).

  1. private void frmbackColor_Click(object sender, EventArgs e)  
  2. {  
  3.     ColorDialog colorDlg = new ColorDialog();  
  4.     if (colorDlg.ShowDialog() == DialogResult.OK)  
  5.     {  
  6.         if (pnControls.BackgroundImage != null)  
  7.         {  
  8.   
  9.             pnControls.BackgroundImage.Dispose();  
  10.             pnControls.BackgroundImage = null;  
  11.         }  
  12.         pnControls.BackColor = colorDlg.Color;  
  13.     }  
  14. }  
  15. //////////////////////////////////          
  16. /// To Add/Change the panel Background Image.  
  17.   
  18. private void frmBackGround_Click(object sender, EventArgs e)  
  19. {  
  20.     OpenFileDialog dialog = new OpenFileDialog();  
  21.     dialog.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";  
  22.     dialog.Title = "Select Your Form background Image File";  
  23.     if (dialog.ShowDialog() == DialogResult.OK)  
  24.     {  
  25.         pnControls.BackgroundImage = Image.FromFile(dialog.FileName);  
  26.          
  27.     }  
  28. }  
  29. ///////////////////////////// 

Delete Controls: To delete all the controls and selected controls. I have used the public variable Selected Control that will store the currently selected control.

  1. /// To Delete a Selected Control from mainPanel(OurForm).  
  2.  private void DeleteSTool_Click(object sender, EventArgs e)  
  3.  {  
  4.      if (SelectedControl != null)  
  5.      {  
  6.          pnControls.Controls.Remove(SelectedControl);  
  7.          propertyGrid1.SelectedObject = null;  
  8.          pnControls.Invalidate();  
  9.      }  
  10.  }  
  11.  //////////////////////////////////  
  12.  /// To Delete All Controls placed in mainPanel(OurForm).  
  13.  private void DeleteATool_Click(object sender, EventArgs e)  
  14.  {  
  15.      pnControls.Controls.Clear();  
  16.      propertyGrid1.SelectedObject = null;  
  17.      pnControls.Invalidate();  
  18.  } 

Add Controls: From the Toolbar the user can add controls to the form (Panel). Now for example to add a DataTimePicker to the form we can use the following code. I created a DataTimePicker at runtime and added the controls to the form (Panel). I have added the runtime control events, like MoverEnter, MouseLeave and MouseDown. Using these events the runtime controls can be moved, resized inside the form (Panel) for design. In the same manner, I have added all the other controls, like TextBox, Button, Label and so on.

  1. ///To Add DateTimePicker Control to Panel(Form).  
  2.   
  3. private void DateTimeTool_Click(object sender, EventArgs e)  
  4. {  
  5.     Random rnd = new Random();  
  6.     int randNumber = rnd.Next(1, 1000);  
  7.     String DatetimeName = "dte_" + randNumber;  
  8.   
  9.     DateTimePicker ctrl = new DateTimePicker();  
  10.     ctrl.Location = new Point(70, 30);  
  11.     ctrl.Name = DatetimeName;  
  12.     ctrl.Font = new System.Drawing.Font("NativePrinterFontA", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));  
  13.     ctrl.Text = DateTime.Now.ToString();  
  14.     ctrl.MouseEnter += new EventHandler(control_MouseEnter);  
  15.     ctrl.MouseLeave += new EventHandler(control_MouseLeave);  
  16.     ctrl.MouseDown += new MouseEventHandler(control_MouseDown);  
  17.     ctrl.MouseMove += new MouseEventHandler(control_MouseMove);  
  18.     ctrl.MouseUp += new MouseEventHandler(control_MouseUp);  
  19.     // ctrl.Click += new EventHandler(control_Click);  
  20.   
  21.     pnControls.Controls.Add(ctrl);  

Runtime Controls Move and Resize: After adding controls to the form (Panel), it needs to be moved, resized and assigned the property to the selected control. All those functions will be added here.

  1. /// RUN time Control Mouse Down Event used for Control Move  
  2. private void control_MouseDown(object sender, MouseEventArgs e)  
  3. {  
  4.     if (e.Button == MouseButtons.Left)  
  5.     {  
  6.         pnControls.Invalidate();  //unselect other control  
  7.         SelectedControl = (Control)sender;  
  8.         Control control = (Control)sender;  
  9.         mouseX = -e.X;  
  10.         mouseY = -e.Y;  
  11.         control.Invalidate();  
  12.         DrawControlBorder(sender);  
  13.         propertyGrid1.SelectedObject = SelectedControl;  
  14.     }  
  15. }  
  16. //////////////////////////////////  
  17. /// RUN time Control Mouse Move Event used for Control Move  
  18. ///   
  19. private void control_MouseMove(object sender, MouseEventArgs e)  
  20. {  
  21.     if (e.Button == MouseButtons.Left)  
  22.     {  
  23.         Control control = (Control)sender;  
  24.         Point nextPosition = new Point();  
  25.         nextPosition = pnControls.PointToClient(MousePosition);  
  26.         nextPosition.Offset(mouseX, mouseY);  
  27.         control.Location = nextPosition;  
  28.         Invalidate();  
  29.     }  

Runtime Class creation: We need to execute code for the runtime Button Click Event. The following function will create a class at runtime and we pass our code part TextBox text to this function from a runtime Button Control Click event.

  1. /// When Runtime Control Clicks this event trigger here we can write our code for runtime control click.  
  2. /// Here in this click event i have Called RunTimeCodeGenerate method this method will create class at runtime and run your code.  
  3.   
  4. ///   
  5. private void control_Click(object sender, EventArgs e)  
  6. {  
  7.    if (rdoMessage.Checked == true)  
  8.     {  
  9.         RunTimeCodeGenerate(txtCode.Text.Trim());  
  10.     }  
  11.     else if (rdoDataTable.Checked == true)  
  12.     {  
  13.         RunTimeCodeGenerate_ReturnTypeDataTable(txtCode.Text.Trim());  
  14.     }  
  15.     else if (rdoXML.Checked == true)  
  16.     {  
  17.         RunTimeCodeGenerate_ReturnTypeDataTable(txtCode.Text.Trim());  
  18.     }  
  19.     else if (rdoDatabase.Checked == true)  
  20.     {  
  21.         RunTimeCodeGenerate_ReturnTypeDataTable(txtCode.Text.Trim());  
  22.     }  
  23.  }  
  24.   
  25. ///This function will create a Runtime Class and add all our runtime code.  
  26.   
  27. public  void RunTimeCodeGenerate(String yourCodeHere)  
  28. {  
  29.     try  
  30.     {  
  31.         string code = @"  
  32.           
  33.              using System;  
  34.              using System.Xml;  
  35.              using System.Data;  
  36.        namespace SHANUFormDesing  
  37.         {  
  38.             public class Program  
  39.             {  
  40.                 public static void Main()  
  41.                 {  
  42.                 YourCodeHere  
  43.                 }  
  44.             }  
  45.         }  
  46.     ";  
  47.           string finalCode = code.Replace("YourCodeHere", yourCodeHere);  
  48.   
  49.         CSharpCodeProvider provider = new CSharpCodeProvider();  
  50.         CompilerParameters parameters = new CompilerParameters();  
  51.         // Reference to System.Drawing library  
  52.         parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");  
  53.         parameters.ReferencedAssemblies.Add("System.Drawing.dll");  
  54.        parameters.ReferencedAssemblies.Add("System.Data.dll");  
  55.        parameters.ReferencedAssemblies.Add("System.Xml.dll");  
  56.        parameters.ReferencedAssemblies.Add("System.dll");  
  57.  // parameters.ReferencedAssemblies.Add("System.Data.SqlClient.dll");  
  58.         parameters.GenerateInMemory = true;  
  59.         // True - exe file generation, false - dll file generation  
  60.         parameters.GenerateExecutable = true;  
  61.   
  62.         CompilerResults results = provider.CompileAssemblyFromSource(parameters, finalCode);  
  63.   
  64.         if (results.Errors.HasErrors)  
  65.         {  
  66.             StringBuilder sb = new StringBuilder();  
  67.   
  68.             foreach (CompilerError error in results.Errors)  
  69.             {  
  70.                 sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));  
  71.             }  
  72.   
  73.             throw new InvalidOperationException(sb.ToString());  
  74.         }  
  75.   
  76.         Assembly assembly = results.CompiledAssembly;  
  77.         Type program = assembly.GetType("SHANUFormDesing.Program");  
  78.         MethodInfo main = program.GetMethod("Main");  
  79.   
  80.         main.Invoke(nullnull);  
  81.     }  
  82.     catch (Exception ex)  
  83.     {  
  84.         MessageBox.Show(ex.ToString());  
  85.     }  
  86.   
  87. }  
  88.   
  89.   
  90.  ///This function will create at Runtime  and this class has a method with return   
  91. //type as DataTable.user can write there own code in textbox to return the data  
  92. // Table and bind to the selected Controls .        
  93.   
  94. public void RunTimeCodeGenerate_ReturnTypeDataTable(String yourCodeHere)  
  95. {  
  96.     try  
  97.     {  
  98.         string code = @"  
  99.           
  100.            using System;  
  101.             using System.Collections.Generic;  
  102.             using System.ComponentModel;  
  103.             using System.Data;  
  104.             using System.Drawing;  
  105.             using System.Text;  
  106.             using System.Windows.Forms;  
  107.             using Microsoft.CSharp;  
  108.             using System.CodeDom.Compiler;  
  109.             using System.Reflection;  
  110.             using System.Data.SqlClient;  
  111.             using System.IO;  
  112.        namespace SHANUFormDesing  
  113.         {  
  114.             public class Program  
  115.             {  
  116.                 public static void Main()  
  117.                 {  
  118.                 }  
  119.                 public static DataTable returnDTS()  
  120.                 {  
  121.                 YourCodeHere;  
  122.                 }  
  123.             }  
  124.         }  
  125.     ";  
  126.         string finalCode = code.Replace("YourCodeHere", yourCodeHere);  
  127.   
  128.         CSharpCodeProvider provider = new CSharpCodeProvider();  
  129.         CompilerParameters parameters = new CompilerParameters();  
  130.         // Reference to System.Drawing library  
  131.         parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");  
  132.         parameters.ReferencedAssemblies.Add("System.Drawing.dll");  
  133.         parameters.ReferencedAssemblies.Add("System.Data.dll");  
  134.         parameters.ReferencedAssemblies.Add("System.Xml.dll");  
  135.         parameters.ReferencedAssemblies.Add("System.dll");  
  136.         // parameters.ReferencedAssemblies.Add("System.Data.SqlClient.dll");  
  137.         parameters.GenerateInMemory = true;  
  138.         // True - exe file generation, false - dll file generation  
  139.         parameters.GenerateExecutable = true;  
  140.   
  141.         CompilerResults results = provider.CompileAssemblyFromSource(parameters, finalCode);  
  142.   
  143.         if (results.Errors.HasErrors)  
  144.         {  
  145.             StringBuilder sb = new StringBuilder();  
  146.   
  147.             foreach (CompilerError error in results.Errors)  
  148.             {  
  149.                 sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));  
  150.             }  
  151.   
  152.             throw new InvalidOperationException(sb.ToString());  
  153.         }  
  154.   
  155.         Assembly assembly = results.CompiledAssembly;  
  156.         Type program = assembly.GetType("SHANUFormDesing.Program");  
  157.         MethodInfo main = program.GetMethod("returnDTS");  
  158.   
  159.         
  160.   object ds   = main.Invoke(nullnull);  
  161.   DataTable dt = (DataTable)ds;  
  162.   foreach (Control pnlCntl in pnControls.Controls)  
  163.   {  
  164.       // DataGridView Data Bind from Data Table and from XML Data Source.  
  165.       if (pnlCntl is DataGridView)  
  166.       {  
  167.           if (pnlCntl.Name == ComboControlNames.SelectedItem.ToString())  
  168.           {  
  169.               DataGridView grid = (DataGridView)pnlCntl;  
  170.               grid.DataSource = dt;  
  171.           }  
  172.   
  173.       }  
  174.       else if (pnlCntl is ListView)  // ListView Data Bind from Data Table and from XML Data Source.  
  175.       {  
  176.           if (pnlCntl.Name == ComboControlNames.SelectedItem.ToString())  
  177.           {  
  178.               ListView lstView = (ListView)pnlCntl;  
  179.               lstView.View = View.Details;  
  180.   
  181.               foreach (DataColumn column in dt.Columns)  
  182.               {  
  183.                   lstView.Columns.Add(column.ColumnName);  
  184.               }  
  185.               foreach (DataRow row in dt.Rows)  
  186.               {  
  187.                   ListViewItem item = new ListViewItem(row[0].ToString());  
  188.                   for (int i = 1; i < dt.Columns.Count; i++)  
  189.                   {  
  190.                       item.SubItems.Add(row[i].ToString());  
  191.                   }  
  192.                   lstView.Items.Add(item);  
  193.               }  
  194.   
  195.   
  196.           }  
  197.       }  
  198.       else if (pnlCntl is ComboBox)  // ComboBox Data Bind from Data Table and from XML Data Source.  
  199.       {  
  200.           if (pnlCntl.Name == ComboControlNames.SelectedItem.ToString())  
  201.           {  
  202.               ComboBox cmbo = (ComboBox)pnlCntl;  
  203.               cmbo.DataSource =dt;  
  204.   
  205.               cmbo.DisplayMember = "ItemName";  
  206.               cmbo.ValueMember = "itemCode";  
  207.   
  208.           }  
  209.       }  
  210.       else if (pnlCntl is ListBox)  // ListBox Data Bind from Data Table and from XML Data Source.  
  211.       {  
  212.           if (pnlCntl.Name == ComboControlNames.SelectedItem.ToString())  
  213.           {  
  214.               ListBox lstBox = (ListBox)pnlCntl;  
  215.               lstBox.DataSource = dt;  
  216.   
  217.               lstBox.DisplayMember = "ItemName";  
  218.               lstBox.ValueMember = "itemCode";  
  219.   
  220.           }  
  221.       }  
  222.   }  
  223.   
  224.                  
  225.   
  226.     }  
  227.     catch (Exception ex)  
  228.     {  
  229.         MessageBox.Show(ex.ToString());  
  230.     }  
  231.   

Points of Interest

I have future plans to extend this application and add functions like New, Save and Open Form, Bind Controls using code from XML and a database.

New features have been added. Now the user can bind data from a Data Table, XML file and from a SQL Server database to a DataGridView, ListView, ComboBox, ListBox at runtime using their code. We will see in detail how to bind data from XML and from a SQL Database. In this article download the latest source code version "SHANUFormDesing_V1.3zip".

Note: In my Zip file's bin folder you can see a "FormDesign.txt". In this text file I have added sample code for the code part to load data. I have attached a "ShanuDataSource.xml" XML file to load data from XML.

I have added all the features that I described previously for New, Save, Open, Cut, Copy and Paste controls, bind data from XML and/or a SQL Server Database. You can download the latest Zip file version V1.3 available for download now at the top of this article. I have many more plans to add more features to this Shanu Form Design Application. Comments are welcome from the readers of this article.

The basic idea for this application originated from my previous article:

Reference Website: The following CodeProject article helped me to create a class and compile at runtime.


Similar Articles