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