.Net C# How to dynamically add controls to a form

Rajesh081725
Posted by Rajesh081725 under C# category on | Points: 40 | Views : 2336
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;



namespace DynamicControls

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();



//This block dynamically creates a TextBox and adds it to the form

TextBox tb = new TextBox();

tb.Name = "tbTest";

tb.Location = new Point(10, 10);

tb.Text = "Some text";

//Hook our textbox up to our generic textbox handler

tb.TextChanged += new System.EventHandler(this.tb_TextChanged);

this.Controls.Add(tb);



//This block dynamically creates a Button and adds it to the form

Button b = new Button();

b.Name = "bTest";

b.Location = new Point(10, 40);

b.Text = "My Button";

//Hook our button up to our generic button handler

b.Click += new System.EventHandler(this.b_Click);

this.Controls.Add(b);

}



//Our generic textbox TextChanged() handler:

private void tb_TextChanged(object sender, EventArgs e)

{

TextBox tb;

tb = (TextBox)sender;

//Prove we can get the name of the TextBox that had its text changed

MessageBox.Show(tb.Name + " TextChanged");

}



private void b_Click(object sender, EventArgs e)

{

Button b;

b = (Button)sender;

//Prove we can get the name of the Button that had its click event called

MessageBox.Show(b.Name + " Click");

}



private void bGetValues_Click(object sender, EventArgs e)

{

//Getting the events to fire is all well and good, but how do we collect

//the data from the form when Save is clicked? I am presuming that there

//are dozens of dynamically created controls on this form. Well, this is

//how

TextBox tb;

//Find the TextBox Control named "tbTest"

tb = (TextBox)this.Controls.Find("tbTest", true)[0];

//Prove we can get the Text that was entered in that textbox

MessageBox.Show(tb.Text);

}


}
}

Comments or Responses

Posted by: Sheonarayan on: 11/10/2012 Level:HonoraryPlatinum | Status: [Administrator] | Points: 10
Hi Rajesh,

Thanks for submitting the code snippet, It would be nice if you can explain the code snippet so that it would be easy for readers to understand this code. Also to make it easily understandable and readable, do place the code snippet in
 
block.

Thank

Login to post response