Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a UserControl that you can drop other controls in it?

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).

like image 746
Juan Avatar asked Nov 21 '10 05:11

Juan


People also ask

How do I add different controls to my form?

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.

Which control is used for multiple item selection?

Hold the CTRL key and click the items in a list to choose them. Click all the items you want to select.

What is a UserControl?

The UserControl gives you the ability to create controls that can be used in multiple places within an application or organization.


1 Answers

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.

like image 173
Cody Gray Avatar answered Oct 05 '22 04:10

Cody Gray