Reputation: 619
How can I automatically increase/decrease TextBox and Windows Form size according to text Length?
Upvotes: 4
Views: 14414
Reputation: 673
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!
Upvotes: 1
Reputation: 11717
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.
Upvotes: 2
Reputation: 14421
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);
}
Upvotes: 10