Joe DePung
Joe DePung

Reputation: 1031

.NET winforms Sub Classed UserControl width keeps increasing

I have created a custom UserControl and then another control that is a subclass of this Usercontrol, but still has its own designer file behind it (the base control is just used for some base functionality... I don't need to 'design' anything on it and actually its height is set to 0).

Everything works as intended at run time, but at design time, it seems like whenever I open the child control in Design mode to work on it, Visual Studio keeps increasing the width on me, by perhaps a couple hundred pixels at a time (or possibly some factor). Before I know it, the thing is 10,000 plus pixels wide and then I have to reset the width in the designer just so it is manageable. This isn't an issue at run time, because the controls width gets set by a parent container it is put in, and the control is anchored to the parent. Its just a pain while designing the controls. Here's just little snippets to better explain what I've done:

public partial class BaseRow : UserControl
{
    public BaseRow()
    {
        InitializeComponent();

        ...
    }
}

Then I want to actually create controls that inherit from this BaseRow, but that I can edit in the designer. So, I go to Add -> UserControl. Then in the class code I change the default created code to inherit from my BaseRow (which inherits from UserControl) so it looks like this:

// changed the inheritance below from UserControl to BaseRow (which inherits from UserControl)
public partial class UnitRow : BaseRow
{
    public UnitRow()
    {
        InitializeComponent();
    }
}

I originally set the width of the objects to 400 in both the base class and the child class in the designer. The base Row sets its Anchor property in its constructor:

this.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

because these controls will all go in a subclassed panel control that will control the width of rows that are added to it.

Everything works fine at run time. The actual width of these 'Row' controls I have created is set correctly and changes appropriately based on its parent subclassed panel control. But when I open the row controls in design mode at design time, the width is constantly getting longer and longer. Everytime the width equal 10,000 or more I manually change it back in the Properties window to a width of 400.

Its not causing any major issue. But it is a real pain. Anyone have any suggestions?

Upvotes: 1

Views: 520

Answers (1)

Adam Kostecki
Adam Kostecki

Reputation: 301

The workaround is to set anchor in the control's Load event handler:

    private void BaseRow_Load(object sender, EventArgs e)
    {
        if ( !DesignMode )
        {
            this.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
        }
    }

Now when you drag&drop control it won't set anchor at design time but will work in runtime.

Upvotes: 2

Related Questions