Wednesday, May 30, 2007

Here is the code to add the controls dynamically to the form and to generate events for the generated controls .the code is an C# code

private void Form1_Load(object sender, System.EventArgs e)
{
int y=16,x=72;
for (int i=1; i<=5;i++) { btn=new Button();
panel1.Controls.Add(btn);
btn.Location=new System.Drawing.Point(x, y);
btn.Text ="Button"+i.ToString();
y=y+30;
btn.Click+=new EventHandler(btn_Click);
}
}

private void btn_Click(object sender, EventArgs e)
{
Button bt=(Button)sender;
MessageBox.Show(bt.Text);

}

Code description

Create a new instance for the button object btn=new Button(); then add the object to the form or panel here I am using panel to place the button control. Then the event is generated in the look it self. The btn_Click event is for the generated buttons.

1 comment:

Anonymous said...

Well written article.