根据文本长度调整文本框和表单大小

时间:2011-11-14 11:46:20

标签: c# winforms visual-studio textbox

如何根据文本长度自动增加/减少TextBox和Windows窗体大小?

4 个答案:

答案 0 :(得分:9)

您可以尝试覆盖OnTextChanged事件,然后根据文字大小更改Width

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

答案 1 :(得分:2)

试试这个,它也会起作用......

这里我将100作为文本框的最小宽度。 “txt”是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;
    }
}

希望它有所帮助。

答案 2 :(得分:1)

这是更好的解决方案。 场景是:我有一个填写表单(usercontrol)的文本框。所以,我想在每次textBox中的行数改变时改变Form Height,但是它的高度不小于MinHeight(常量)

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

希望这有帮助!

答案 3 :(得分:-2)

在属性中将宽度设置为自动

相关问题