kalenpw kalenpw - 29 days ago 10
C# Question

C# TextBox same size as form missing anchor or dock property

I am trying to have a TextBox that spans the entire height and width of its form. I initially set the width and height to auto, but that causes it to grow as more text is entered where I would prefer it to always be 100% of the width and height.

I read about the dock and anchor property here C# - Stretching a textbox to fit the containing window and based off the code there and at MSDN I would like to do something like

TextBox foo = new TextBox();
foo.Dock = DockStyle.Fill;

or

foo.Anchor = AnchorStyles.Left;


however, when I try that I am informed that TextBox does not contain a definition for anchor or dock. I have tried this with a Button as well as a RichTextBox so the issue doesn't appear to be with the form type. How can I set the Anchor or Dock property of a TextBox with c#?

Answer

TextBox.Dock and TextBox.Anchor apply to the WinForms TextBox not WPF's. For WPF you can achieve the same behavior with VerticalAlignment and HorizontalAlignment properties as indicated below:

        var foo = new TextBox();

        foo.VerticalAlignment = VerticalAlignment.Stretch;
        foo.HorizontalAlignment = HorizontalAlignment.Stretch;
Comments