GroupBox: Adjust size according to text length

泪湿孤枕 提交于 2019-12-13 07:02:12

问题


Is there an easy way to have a GroupBox auto resize its width depending on the length of the string in the Text property?

Say I fit the width by hand (in Design Mode) when the Text = "Text1" then, when the program is running, I update it to Text = "This is the new text!" I would like the width to auto expand instead of wrapping over to the next line.

Thanks!


回答1:


You need to get the width of the string using the Graphics.MeasureString Method

Here the simple example, hint, the width is depending of the size of the font not the font-size of your GroupBox property.

SizeF stringSize = new SizeF();
private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    string measureString = "this is your text";
    Font stringFont = new Font("Arial", 17);

    // Measure string.
    stringSize = e.Graphics.MeasureString(measureString, stringFont);
}

private void button1_Click(object sender, EventArgs e)
{
    groupBox1.Text = "this is your text";
    groupBox1.Width = (int)stringSize.Width;
}

I hope it will helps you.




回答2:


I believe you can set the AutoSize property to true.



来源:https://stackoverflow.com/questions/14737392/groupbox-adjust-size-according-to-text-length

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