Tuesday, March 15, 2011

How to autosize User control when it's shown

Hello, I have a Winforms project with a bunch of User controls. I'd like the user control to move itself to be at the 1,1 position relative to its container (whether it's a form or a Panel control). And resize itself to be able to fit half the container.

What event can I respond to in the UserControl to be able to do this without any code having to be written in the container (e.g. the form or panel).

From stackoverflow
  • The Paint event should work, unless I'm missing something.

  • You could use the basic Load event.

    The code could be like this:

    private void UserControl1_Load(object sender, EventArgs e)
    {
        Control parent = this.Parent;
        if (parent != null)
        {
            this.Location = new Point(1, 1);
            this.Width = (parent.Width / 2);
            this.Height = (parent.Height / 2);
        }
    }
    

0 comments:

Post a Comment