Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding controls to User Controls dynamically

I want to add a control to a user control in an event handler (like a button click event).

I'm trying to add a datagridview lookup control dynamically, but I couldn't get that to work, so I tried just adding a button with this code:

private void btnCreateNewButton_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Location = new Point(100, 640);
    btn.Size = new Size(100, 30);
    btn.Text = "Click Me";
    btn.Click += (s, ea) => MessageBox.Show("New button clicked");
    this.Controls.Add(btn);
}

When i click my Create New Button, no button appears.

If I add the exact same code into a form instead of a usercontrol, the button is created and displays as intended, but in a user control nothing happens. In the user control I've also tried

this.Parent.Controls.Add(btn) and
this.ParentForm.Controls.Add(btn) 

but to no avail.

Anybody got any ideas?

Thanks, Ciaran.

like image 620
Ciaran O'Neill Avatar asked Nov 05 '22 22:11

Ciaran O'Neill


1 Answers

You place your button on 100,640 point. Please ensure that your user control can accomodate your dynamic button. Otherwise, you won't see it. I used your code and it worked fine for me, just ensure the proper size of both parent form and user control.

like image 161
Valentin V Avatar answered Nov 11 '22 09:11

Valentin V