Reputation: 10557
I want to be able to set the number of lines in a multilined TextBox
.
I've tried the following:
int initHeight = textBox1.Height;
textBox1.Height = initHeight * numOfLines;
But this makes it too large when numOfLines
gets large. So then I tried this:
float fontHeight = textBox1.CreateGraphics().MeasureString("W", textBox1.Font).Height;
textBox1.Height = fontHeight * numOfLines;
But this was too small when numOfLines
was small, and too large when numOfLines
was large.
So I'm doing SOMETHING wrong... any ideas?
Upvotes: 2
Views: 4329
Reputation: 7351
This would set the exact Width
& Height
of your multi line Textbox:
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height + Convert.ToInt32(textBox1.Font.Size);
Upvotes: 4
Reputation: 564851
From the documentation of Graphics.MeasureString:
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
As such, you should use one of these overloads, such as this one, which allow you to specify StringFormat.GenericTypograpic
to get the required size.
Try this:
float fontHeight;
using (var g = textBox1.CreateGraphics())
fontHeight = g.MeasureString("W", textBox1.Font, new PointF(), StringFormat.GenericTypograpic).Height;
Upvotes: 2
Reputation: 4266
Something like this should work:
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height;
This was from C# Resize textbox to fit content
Upvotes: 3
Reputation: 67135
What you are doing should work, but you need to set the MinimumSize
and MaximumSize
I am not 100% positive, but I think this constraint will still hold if height is set via code
Upvotes: 2