C# usercontrol how to access all child controls

10,930

You need to expose the properties you want to modify in your user control. For example, to change the column count property of the table layout control, from your user control, you have to expose the ColumnCount property:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public int ColumnCount
    { 
        get
        {
            return this.tableLayoutPanel1.ColumnCount;
        }

        set
        {
            this.tableLayoutPanel1.ColumnCount = value;
        }
    }
}

You can also then start to use some attributes to control how your user control is displayed in Visual Studio, for example, the above can be modified like so:

[DefaultProperty("ColumnCount")]
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    [Description("Gets or sets the column count of the table layout.")]
    [Category("TableLayout")]
    [DefaultValue(2)]
    public int ColumnCount
    { 
        get
        {
            return this.tableLayoutPanel1.ColumnCount;
        }

        set
        {
            this.tableLayoutPanel1.ColumnCount = value;
        }
    }
}

This sets the default property of the entire user control to "ColumnCount", and gives the column count property a description, a default value of 2, and sets in what category it should be displayed in the designer's properties window. There is a lot more that can do with a user control to add design time support.

Share:
10,930
Toto
Author by

Toto

C# developper

Updated on June 23, 2022

Comments

  • Toto
    Toto almost 2 years

    I defined a custom panel with a table layout panel inside. However when I used this control on a winform I do not have access to the table layout panel properties. (I want for instance add a column or dock an other control in a cell). I try to changed the modifier property to public, but it still does not work. What can I do in order to see and change the panel layout properties ?

    In fact, the question can be more generic : how to access/modify/move controls contained in a custom usercontrol ?

    Thx

  • Toto
    Toto over 14 years
    Ok for adding some property to the designer's properties window. But can we also add graphic support like the rows and the columns to be displayed in the designer ? Or the edit row and columns tools ?