简体   繁体   中英

c# create a user control on button press, won't show

counters.Add(new Counter());
foreach (Counter con in counters)
{
   con.Show();
   con.Top = this.Top;
   con.Left = this.Left;
}

counter is a very basic UserControl I made with 3 buttons and textbox . I'm trying create a draggable Counter, I can see the counter on the list (counters) but I can't see it anywhere on screen.

I was wondering if new Counter() is enough to create the UserControl on screen. (i mean to create this "counter" object dynamically)

Control needs to have a parent that hosts the control. The parent control can be either a form or another container control. When you want to add your control to the hosting control, add the instance into the Controls collection of the hosting control like this:

var counter = new Counter();
var form = new Form();
form.Controls.Add(counter);
form.Show();

I think user Controls need to be in some sort of container, for example a flowLayoutPanel or your instance of the Form class itself to visually exist.
You need to call CONTAINERINSTANCE.Controls.Add(con).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM