Sunday, April 3, 2011

Adding controls to User Controls dynamically

Hi,

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.

From stackoverflow
  • 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.

    Ciaran : Thanks for that, it was displaying beneath the control for some reason. I needed to call BringToFront()
  • Most likely it is just that your button is being placed out of the bounds of the parent control and/or behind another control. I don't believe that UserControls or Forms are special in respect to adding controls at run-time, but a simple difference may be that Forms are by default re-sizable whereas UserControls aren't? Either way I don't think either Control type will automatically resize to fit all their child controls, so it's quite easy to put a new/dynamic control in the wrong place and have it not be visible.

0 comments:

Post a Comment