C# Resize textbox to fit content

2019-01-14 11:45发布

问题:

I'm writing a program where the user should be able to write text in a textbox. I'd like the textbox to resize itself, so it fit the content. I've tried the following:

private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
{
    System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
    System.Drawing.SizeF mySize = e.Graphics.MeasureString("This is a test", myFont);
    this.textBoxTitle.Width = (int)Math.Round(mySize.Width, 0);
}

I get an error saying that Graphics doesn't work for TextChangedEventArgs. Is there another way I can resize the textbox?

回答1:

You should try a code something like below. It has worked for me well.

private void textBox1_TextChanged(object sender, EventArgs e)
{
  Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
  textBox1.Width = size.Width;
  textBox1.Height = size.Height;
}

For more information refer to TextRenderer.MeasureText()



回答2:

I am adding this answer as I do not see the fixed width aspect of a textbox being discussed in any of the other. If you have a fixed width for your textbox, and you want to adjust only its height you can do something like the following:

Something like this gives the height of the text as how it is drawn in the multiline wordwrapped textbox itself:

SizeF MessageSize = MyTextBoxControl.CreateGraphics()
                                .MeasureString(MyTextBoxControl.Text,
                                                MyTextBoxControl.Font,
                                                MyTextBoxControl.Width, 
                                                new StringFormat(0));

I am not sure what StringFormat should be but the values StringFormatFlags do not seem to apply to a default TextBox make up.

Now with MessageSize.Height you know the height of the text in the textbox.



回答3:

Your binding to the wrong event, and you cannot use the graphics object in the TextChangedEventArgs object.

Try using the TextChanged event. The following snippet is working:

public Form1()
{
    InitializeComponent();

    this.textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
}

void textBox1_TextChanged(object sender, EventArgs e)
{
    System.Drawing.SizeF mySize = new System.Drawing.SizeF();

    // Use the textbox font
    System.Drawing.Font myFont = textBox1.Font;

    using (Graphics g = this.CreateGraphics())
    {
        // Get the size given the string and the font
        mySize = g.MeasureString(textBox1.Text, myFont);
    }

    // Resize the textbox 
    this.textBox1.Width = (int)Math.Round(mySize.Width, 0);
}

}



回答4:

I had the same problem and I solved it in a simpler way.

I used the AutoSize property of a Label control.. I added an invisible label to my form, set its AutoSize property True. When the I need to change the size of my TextBox I use this code:

MyLabel.Text = MyTextBox.Text;
MyTextBox.Size = MyLabel.Size;

I set the Maximum and Minimum Size of the label for better results. Have Fun



回答5:

You will need to use the CreateGraphics() method of the form to create the Graphics instance to measure the string on.

The TextChangedEventArgs class does not have a Graphics property, that is a property of the PaintEventArgs class passed in to the Paint event handler



回答6:

Try this:

using System.Drawing;
...

private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
{
    // Determine the correct size for the text box based on its text length   

    // get the current text box safely
    TextBox tb = sender as TextBox;
    if (tb == null) return;

    SizeF stringSize;

    // create a graphics object for this form
    using(Graphics gfx = this.CreateGraphics())
    {
        // Get the size given the string and the font
        stringSize = gfx.MeasureString(tb.Text, tb.Font);
    }

    // Resize the textbox 
    tb.Width = (int)Math.Round(stringSize.Width, 0);

}

Essentially you create your own Graphics object for the form, then measure it based on the text and font of the TextBox. The using will properly dispose the Graphics object - your previous code would have leaked horribly!



回答7:

Did you try to set yourTextBox.AutoSize = true;? This property may be hidden in the GUI designer, but you can set it in the form constructor right after InitializeComponent(); call.



回答8:

Graphics.Measure string you can do o PaintEventArgs, not on TextChangedEventArgs

What I think you want is this

System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
Graphics graphics = this.CreateGraphics();
SizeF textSize = graphics.MeasureString("This is a test", myFont);

The problem is that you just cannot create a Graphics object by simply allocating it since it has no public constructor, so you should better go and use TextRenderer.MeasureText, as done in http://msdn.microsoft.com/en-us/library/y4xdbe66.aspx

TextRenderer is less accurate because it uses GDI and Graphics uses GDI+, so maybe you should leave a little margin on the value you get from the Width property.

Hope this helps



回答9:

Whatever the aim is.

If the size of the textbox should be dynamically set up based on the string, which should be the text inside this box, there is no nice option.

Reasons : MeasureString uses usual string formatters as delimiters for its own width and height. Means, carriage return and line feed are parsed, too. Resulting in a sizeF.Width and sizeF.Height.

Depending on the string( and its font and number of lines ) these both variables can carry values, which are sometimes useless to be used as width/height values of a textbox ( because they can be bigger than the parentform's values and this would resize the textbox to a size, with left and bottom borders beyond those of the parent form).

Some solutions are still available, depending on the aim, one would like to achieve.

One idea would be : Create a textbox in designer, size = 100 X 100. enable word-wrapping.

In the OnTextChanged event handler of the textbox, we just resize the textbox's width to a value, defined by ourself (e.g. parentform.Width or another hard value ).

This would cause the word wrap to recalculate the string in the textbox and this would rearrange all the characters inside the textbox, because word wrap is enabled.

The height of the textbox could can be set hard to parentform.Height, for example.

BUT, better : set the height dynamically,based on the Y value of the ReturnValue (Point) of the method texbox.GetPositionFromCharIndex(textbox.TextLength -1 ). Then, with Math.Min() determine, which is smaller ( either parentform.Height or Point.Y ) , and reset the textbox size to new Size(previousDeterminedWidth, nowDeterminedHeight).

Please keep in mind ( if scrollbars are enabled ) to add about 17 pixs to Your width calculation.

Best regards