Edgar
Edgar

Reputation: 1120

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.

Upvotes: 0

Views: 3806

Answers (2)

Liath
Liath

Reputation: 10191

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)

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 6

Related Questions