Change the TextBox width to fit my text?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Visual Studio 2003 .NET C#

I am trying to change the width of a textbox at run time, to fit in the text
it contains. How can I do this?

Thanks

Steve
 
Steve said:
Visual Studio 2003 .NET C#

I am trying to change the width of a textbox at run time, to fit in the
text
it contains. How can I do this?

System.Windows.Forms.TextBox myTextBox = new System.Windows.Forms.TextBox();
myTextBox.Width = x;
 
but how do I calculate the value of x? All I have is the Length of my
string, the lenght for instance of the string "Pumping Station" is 15, but if
I were to set the Width of my text box to 15, then this would not be the
correct width, as the width is in pixels I think. I guess the question is,
how do you calculate the width of length ;-)
 
Well, this is one way of accomplishing it:

Graphics g = Graphics.FromHwnd(textBox1.Handle);
SizeF f = g.MeasureString("String to fit", textBox1.Font);
textBox1.Width = (int)(f.Width);
// textBox1.Height = (int)(f.Height); // if required...
textBox1.Text = "String to fit";


Visual Studio 2003 .NET C#

I am trying to change the width of a textbox at run time, to fit in the text
it contains. How can I do this?

Thanks

Steve
 
Steve said:
but how do I calculate the value of x?

Sorry Steve, guess I should have guessed you already knew that. Haven't
checked Siva's code, but that's the idea you want....
 
Back
Top