Resize textbox and form size according to Text Length

家住魔仙堡 提交于 2019-12-22 08:55:11

问题


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



来源:https://stackoverflow.com/questions/8121090/resize-textbox-and-form-size-according-to-text-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!