Adding Controls at Runtine

  • Thread starter Thread starter cox
  • Start date Start date
C

cox

Does anyone have any idea how I can add controls at runtime including event
handlers using C#.

I would very much appreciate some sample code.

The biggest concern I have is that I cannot give a control a name using
Control.Name = "XXXX"
 
Basically you can just copy code that is automatically generated when you
use the designer (take a look at the code generated in InitializeComponent.
The name of the control is the name you gave a particular instance of the
control. Here is a sample button, including an event handler, generated
dynamically on the form's Load event:

private void Form1_Load(object sender, System.EventArgs e)
{
Button btn = new Button();
btn.Text = "New Button";
btn.Location = new System.Drawing.Point(10,10);
btn.Size = new System.Drawing.Size(80, 20);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}

private void btn_Click(object sender, System.EventArgs e)
{
MessageBox.Show("I am clicked");
}

Regards,
 
Thanks for the response. More specifically though how can I create an array
(so to speak) of a control like if I wanted to create several listboxes
(number of listboxes to be determined at runtime) how can I do that?
 
OK, I am sticking with my original sample, but I have changed it to use an
array of buttons. I am using one event handler for all buttons, but the
event handler determines wich button fired the event and takes action
accordingly. Make sure to declare the array of buttons as private date
member of the form:

private Button[] btn;

Then declare the array of buttons (including the size of the array) during
runtime, in the example in the form Load event:

private void Form1_Load(object sender, System.EventArgs e)
{
btn = new Button[4];

for (int i = 0; i < 4; i++)
{
btn = new Button();
btn.Text = "New Button " + i.ToString() ;
btn.Location = new System.Drawing.Point(10,i * 30);
btn.Size = new System.Drawing.Size(100, 20);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}

Then determine in the event handler which button fired the event and take
the correct action.

private void btn_Click(object sender, System.EventArgs e)
{
if ((sender as Button) == btn[0] )
{
MessageBox.Show("btn[0] clicked");
}
else if ((sender as Button) == btn[1])
{
MessageBox.Show("btn[1] clicked");
}
else
{
MessageBox.Show("another button clicked");
}
}

I guess something similar should be possible for listboxes.

Regards,
 
Back
Top