Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# usercontrol how to access all child controls

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

like image 872
Toto Avatar asked Feb 28 '23 09:02

Toto


1 Answers

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.

like image 98
Stuart Grassie Avatar answered Mar 11 '23 06:03

Stuart Grassie