In WinForms, how can I create a UserControl
that when I put on my form I can then add other controls inside by dragging them from the toolbox, the same way as with all containers controls (panels, group boxes, etc)? I've tried to add controls by dropping them in my control but then when I move my control the controls I added stay right where they are, which wouldn't happen if instead of my control I would use a Panel
(the other controls would move with the panel).
Add the control by drawingSelect the control by clicking on it. In your form, drag-select a region. The control will be placed to fit the size of the region you selected.
Hold the CTRL key and click the items in a list to choose them. Click all the items you want to select.
The UserControl gives you the ability to create controls that can be used in multiple places within an application or organization.
Unlike a Panel
control for example, a UserControl
does not act as a container control once it is placed on another form. There is full design-time support while you are designing the UserControl
itself, but its default behavior does not allow it to act as a constitutent control after it has been placed on another form. This is why you are unable to add other controls to it by dragging them from the toolbox.
In order to add this type of behavior to a UserControl
, you need to add the DesignerAttribute
to the definition of your custom UserControl
class. For example:
using System.ComponentModel;
using System.ComponentModel.Design;
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class MyUserControl : System.Windows.Forms.UserControl
{
//...your code here
}
(See the relevant MSDN article for further reading.)
If you want to implement full designer support for nested controls inside your UserControl
, this is slightly more difficult. For a more comprehensive discussion, see this article on CodeProject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With