Create Controls Dynamically with Events in Windows Form

Step 1: Create new windows form application.

Step 2: Create win from like below.

 

Step 3: Write the following code

  1. using System;  
  2. using System.ComponentModel;  
  3. using System.Drawing;  
  4. using System.Windows.Forms;  
  5. namespace DynamicControls   
  6. {  
  7.     public partial class Form1: Form   
  8.     {  
  9.         public Form1()   
  10.         {  
  11.             InitializeComponent();  
  12.         }  
  13.         private void button1_Click(object sender, EventArgs e)   
  14.         {  
  15.             TextBox txt = new TextBox();  
  16.             this.Controls.Add(txt);  
  17.             txt.Location = new Point(100, 20);  
  18.             txt.Validating += new CancelEventHandler(txt_Validating);  
  19.         }  
  20.         private void txt_Validating(object sender, EventArgs e)   
  21.         {  
  22.             MessageBox.Show("Textbox validated.");  
  23.         }  
  24.     }  
  25. }  
In code in button click event we create textbox control dynamically and add it to form’s Control collection. Also we set location property of textbox. By using following line of code we bind validating event to textbox.

  1. txt.Validating += new CancelEventHandler(txt_Validating);  
Step 4: Run the application.

Step 5: Click on Create button. It will create textbox control on form as follows.

 

Step 6: Type some text in textbox and leave the control then event will raise and it gives message as follows.

 
Ebook Download
View all
Learn
View all