Resize textbox and form size according to Text Len

2019-05-07 05:23发布

问题:

How can I automatically increase/decrease TextBox and Windows Form size according to text Length?

回答1:

You can try overriding the OnTextChanged event, then changing the Width depending on the size of the text.

protected override OnTextChanged(EventArgs e)
{
    using (Graphics g = CreateGraphics())
    {
        SizeF size = g.MeasureString(Text, Font);
        Width = (int)Math.Ceiling(size.Width);
    }
    base.OnTextChanged(e);
}


回答2:

Try this, it will also work...

Here I have taken 100 as minimum width of textbox. "txt" is TextBox.

const int width = 100;

private void textBox1_TextChanged(object sender, EventArgs e)
{
    Font font = new Font(txt.Font.Name, txt.Font.Size);

    Size s = TextRenderer.MeasureText(txt.Text, font);
    if (s.Width > width)
    {
        txt.Width = s.Width;
    }
}

Hope it helps.



回答3:

Here is better solution. Scenario is: I have a textbox that Filled on form (usercontrol). So, I want to change Form Height each time number of line in textBox change, but its height is not less than MinHeight (a constant)

private void ExtendFormHeight()
        {
            int heightChanged = txtText.PreferredSize.Height - txtText.ClientSize.Height;
            if (Height + heightChanged > MinHeight)
            {
                Height += heightChanged;
            }
            else
            {
                Height = MinHeight;
            }
        }

Hope this help!



回答4:

set width to Auto in properties