简体   繁体   中英

C# WinForms add controls programmatically

Can someone suggest the best way to achieve my goal?

So, I have a form with three buttons. What I want is, depending on what button is pressed on panel should be shown different controls (user control). I made this in a simple way: all are added from the beginning, I just make change to the visibility. But what would be nice is, if someone can suggest a more appropriate way, because there is no need to have objects created from beginning.

You can always create the appropriate UserControl , and add it to the Panel.Controls at runtime. This will allow you to create the control(s) as needed, instead of on initialization of your Form.

I would indeed create the controls at design time - if there's advantage no to dynamically create them. Why complicate matters?

If there are a number of controls I would put them all in a panel (within the panel you've already mentioned) so you're only changing the visibility of a single control (the panel) rather than each one within it.

When you press the appropriate button show the appropriate panel (and remember to hide the others in case you've previously shown them)

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