C# WinForms add controls programmatically - c#

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)

Related

Best way to add "dynamic" controls?

My program will prompt the user for a number, i.e. 25. The program will then start the "main form" with 25 controls (textbox). The 25 (or whatever number) of textboxes (or whatever control) will need to be formatted evenly. I will also need to be able to retrieve the text (or another property if I use another control) in order, from left to right and up to down. What is the best method of approaching this?
Using WPF MVVM. In a .XAML file, create a DataTemplate with the DataType of a ViewModel that will provide the binding for your TextBoxs, lets call this the TextboxViewModel. Then using a ItemsControl element with an ItemsSource of TextboxViewModel. You'll be able to instantiate as many TextBoxs as you want and be able to get the result by browsing through your list of TextboxViewModel.
Supposing you are using Windows Forms here.
Dynamically create the X controls and add them to the Controls collection of your form. To ease the access to them you can store their reference in a List and set some event handlers too, depending on your needs. You just need to calculate their positions while you add them.
If WinForms, this is exactly what the FlowLayoutPanel is for. Just add the controls to it and they will arrange themselves automatically, wrapping down to the next row as needed. As Mihai already suggested, you could also keep reference to those controls in a List.
Another option would be to use a TableLayoutPanel. It's a little more difficult to learn and use, but is much more flexible and powerful.

Create controls dynamically or create controls in a side form? C# winforms

I have a form full of controls, and there is no room for other controls. On the bottom of the form I have a panel with some controls on it.
My goal is that when a certain button is clicked, the original panel on the bottom will be replaced with another panel that contains controls which could be created before the program starts, meaning these controls in the panel do not need to be created dynamically. The replace action would be executed by setting each panel's visible field to it's matched value.
I have thought of two ways of doing this - either creating the new panel (and it's controls) dynamically and adding it to the form instead of the original, or creating the new panel in another form and when the relevant button is clicked the panel being taken from that form and added to the required form (by creating an instance of the new form and making it's panel's modifier public). The "side form"'s purpose is only to create that panel, it has no functionality of it's own.
The advantages of creating the new panel dynamically:
There is no need to create a zero-functionality form.
The advantages of creating the new panel in a side form:
It's very clear which controls are added to the new panel and their positions.
It's very easy to set the location and other fields of the controls in the new panel.
Which way is better?
Thanks!
Have you considered TabControl? That seems a good fit for your needs. Other controls I can think of are StackPanel (Can be fairly easily done for Windows Forms) or OutlookBar like control (again a user control).
Simplest and quickest way seems to be TabControl.
Edit:
SideForm is a different windows form I suppose. So if you are thinking to make controls public and then change their visibility etc, please don't. Use delegates to handle SideForm's events in MainForm.
As you mentioned, there is no room for more controls, I would suggest more screens rather than just one. Having said that I do not know much about your current UI design and functionality so it's up to you.
I would say having the controls hidden and just playing with the Visibility is fine. This means that you do not have to worry about positioning of controls, anchoring and docking at runtime. The problem could well be loading of form. Having huge number of controls having a lot of data associated with them may slow things down.
IMO the best way would be to utilise user controls for this purpose. Simply create one user control per panel you wish to show/hide and place your controls inside. This way you will have both: the designer and the "extra form" you wanted.

difference between Panel and UserControl c#

Could someone please tell me the differences between using a Form, Panel or a UserControl.
A form is a control and a container for other controls. A form is the base unit of a windows application.
A panel is a control and a container for other controls.
A usercontrol is a user defined control.
See:
Windows Forms
Windows Forms Controls
Windows Forms Overview
In Windows Forms, a form is a visual
surface on which you display
information to the user. You
ordinarily build Windows Forms
applications by adding controls to
forms and developing responses to user
actions, such as mouse clicks or key
presses. A control is a discrete user
interface (UI) element that displays
data or accepts data input.
When a user does something to your
form or one of its controls, the
action generates an event. Your
application reacts to these events by
using code, and processes the events
when they occur. For more information,
see Creating Event Handlers in Windows
Forms.
According to MSDN the Panel class is "Used to group collections of controls", while the User Control "Provides an empty control that can be used to create other controls".
You are right: this doesn't help you a lot to decide whether you should use a Panel or a User Control.
One of the differences is that a Panel is a ScrollableControl, while a UserControl is a ContainerControl (which is also a ScrollableControl). So if you want ContainerControl functionality, consider to use a UserControl.
You'll probably don't know what a ContainerControl does, so what you can't do with a Panel, hence the following might be more useful:
In object oriented programming, and so also in Winforms, whenever you want a class that behaves like another class, but only slightly different, you consider to derive from the other class.
So if you want a button that changes color when pressed, and returns to its original color when pressed again, (like an on-off button), you might consider to derive from class Button, or maybe from class CheckBox-in-the-shape-of-a-button.
By making it a separate class, you can reuse the code in similar situations. Whenever you will only use it once, then usually we won't bother to make it a special class. We will usually not make a special class for "The Select button in my form, which does ... when clicked", but if you will use this button in ten different forms, then it is probably wiser to create a SelectButton class.
Similar, if you have a group of controls, with some behaviour, and you plan to use that in different forms, consider to create a User Control, where you put this behaviour. The nice thing is that the code of this behaviour is hidden inside the control. Users of your UserControl only have to know what it does, not how this is done. You might even want to hide how this is done, so users (= code, not operators) can't access it
A panel is more or less like a GroupBox without a surrounding rectangle: consider to use it instead of a User Control if you will be using it only inside this Form. Similar to how you would us a "Button that does ... when clicked": because you use it only here, you don't derive from it.
I seldom use a Panel. The derived classes: TabPage, SplitterPanel, ... are more likely to be used only in this form.
Whenever I need combinations of several controls, especially if they interact with each other. For instance, if you have a text box and a label that describes what is in the textbox and an OK button that processes the text in the text box. In that case I usually make it a UserControl.
I could have derived from a Panel and add a Label, TextBox and Button, but then users could mess up with my Panel by adding other items, or calling Panel functions that would mess with my functionality.
Come to think of it: using a class derived from a Panel vs using a UserControl is similar to deriving vs aggregation / composition: If you aggregate, you can limit access to functionality, if you derive, users can access all parent functionality.
So if you only want limited functionality: show / no show, maybe size and position, background, but not much more: consider to create a UserControl. If you want the possibility to change the behaviour, consider to use a Panel, especially if you will use it in only one form.

How to implement a-form-inside-a-form with runtime embedded forms switching?

I need to implement TabControl-like behaviour with manual (on event, on a button click for example) pages switching and having all pages designed and implemented as separate forms. A form to be incorporated (as a panel control) inside main form and replaced by another form as needed.
How to achieve this?
PS: The reason why I don't want to use TabControl instead is because there are going to be too many tabs - I'd prefer to present the list of them as a TreeView and instantiate on demand. The another reason comes from another project of mine - there I am going to implement plug-ins, where a panel inside main window will be provided by a class loaded dynamically and will be runtime-switchable.
I need to implement TabControl-like behaviour with manual (on event, on a button click for example) pages switching and having all pages designed and implemented as separate forms
May I ask why this is a requirement? It seems like the logical approach would be to create a set of UserControls. You can place a UserControl in a form, and you can place a UserControl in a tab. You get modularity without the headache of implementing a very odd requirement which is a use case that the API developers obviously did not think was valid. I just can't think of a good reason to take the route you have suggested.
I did similar thing once, and for that reason, I have ReplaceControl method, which I paste below:
static public void ReplaceControl(Control ToReplace, Form ReplaceWith) {
ReplaceWith.TopLevel=false;
ReplaceWith.FormBorderStyle=FormBorderStyle.None;
ReplaceWith.Show();
ReplaceWith.Anchor=ToReplace.Anchor;
ReplaceWith.Dock=ToReplace.Dock;
ReplaceWith.Font=ToReplace.Font;
ReplaceWith.Size=ToReplace.Size;
ReplaceWith.Location=ToReplace.Location;
ToReplace.Parent.Controls.Add(ReplaceWith);
ToReplace.Visible=false;
}
Only thing left to do is to create some control manually on the form, as the placeholder for your Form. Use label, for example.
You could do this with an MDIForm as the main form, and then plain-old Forms as the separate forms. Or you could encapsulate each element's functionality as a UserControl which you can then swap out on your form in code.
The advantage of encapsulating your UI elements as UserControls is that if, for whatever reason, you need them to become forms in your application, you can just drop the UserControl on a form.
Update: Since you want to use a TreeView to select what the user is looking at, you definitely want to do this as a bunch of UserControls. The layout is simple: TreeView on the left, and whichever control is active on the right.
There's no need to justify not using a TabControl - tabs are the worst UI element in history.

To Show a Control in two Windows Forms

I have inherited a control from Panel-Class.
I have added some events to this control. I gave move - ability to this control
and so on ..
I have two display screens. I have a main program where the inherited
panel is displaying an image on a small area. I want to show this panel
fullscreen on a second.
I created a new form and use the same control... But i can not move both screens
together. What should I do ?
If you want to be able to manipulate both forms at the same time, show the second form with Show() instead of ShowDialog(). You can certainly pass the original panel to the second form and add it to the form's Controls collection. I am not sure if this is the best way to do it (sharing one control across two forms), but I don't know your requirements either.
I wouldn't use a second form, but a second 'mode' (fullscreen vs. not) on your existing form.
You can have 2 panel controls, or just one and resize.
I think this kind of behaviour calls for a model-view pattern. If that's implemented, the rest should fall into place.
The problem is that you only have one instance of your inherited panel. You actually have to make another "copy" of it, a new instance, before you can add it to the other form.
Mypanel mypanel1 = new Mypanel();
Mypanel mypanel1copy = new Mypanel();
You can either edit these instances to contain the same data all the time through the run, or use something like "Deep Copy":
How do you do a deep copy of an object in .NET (C# specifically)?
Keep in mind, that any changes to mypanel1 should be done to mypanel1copy, too.

Categories