Change the Textbox height?

后端 未结 21 2200
心在旅途
心在旅途 2020-12-09 07:24

How do I change the height of a textbox ?

Neither of the below work:

this.TextBox1.Size = new System.Drawing.Size(173, 100);
         


        
21条回答
  •  失恋的感觉
    2020-12-09 08:07

    The following code added in your constructor after calling InitializeComponent() will make it possible to programmatically set your text box to the correct height without a) changing the Multiline property, b) having to hardcode a height, or c) mucking with the Designer-generated code. It still isn't necessarily as clean or nice as doing it in a custom control, but it's fairly simple and robust:

    if (txtbox.BorderStyle == BorderStyle.None)
    {
        txtbox.BorderStyle = BorderStyle.FixedSingle;
        var heightWithBorder = txtbox.ClientRectangle.Height;
        txtbox.BorderStyle = BorderStyle.None;
        txtbox.AutoSize = false;
        txtbox.Height = heightWithBorder;
    }
    

    I decided to make it cleaner and easier to use by putting it in a static class and make it an extension method on TextBox:

    public static class TextBoxExtensions
    {
        public static void CorrectHeight(this TextBox txtbox)
        {
            if (txtbox.BorderStyle == BorderStyle.None)
            {
                txtbox.BorderStyle = BorderStyle.FixedSingle;
                var heightWithBorder = txtbox.ClientRectangle.Height;
                txtbox.BorderStyle = BorderStyle.None;
                txtbox.AutoSize = false;
                txtbox.Height = heightWithBorder;
            }
        }
    }
    

提交回复
热议问题