Resize a Control to Fit Text

Provided by the FMS Development Team

There are times when you want a form to dynamically resize one or more controls to fit their entire text. For example, given a specific text value, you want a textbox that grows wide enough to show the entire string. .NET provides various measurement functions in the System.Graphics library to accomplish this.

The following example code shows how to make a textbox wide enough to accommodate its text.

// C#

   // Determine the correct size for the text box based on its text length     

   // Create a new SizeF object to return the size into

   System.Drawing.SizeF mySize = new System.Drawing.SizeF();

   // Create a new font based on the font of the textbox we want to resize

   System.Drawing.Font myFont = new System.Drawing.Font(this.textBox1.Font.FontFamily, this.textBox1.Font.Size);

   //

   // Or, use this for a specific font and font size.

   // System.Drawing.font myFont = new System.Drawing.Font("Verdana", 8);

 

   // Get the size given the string and the font

   mySize = e.Graphics.MeasureString("This is a test", myFont);

 

   // Resize the textbox to accommodate the entire string

   // Me.TextBox1.Width = mySize.Width;

   this.textBox1.Width = (int) Math.Round(mySize.Width, 0);

 

' VB

   ' Determine the correct size for the text box based on its text length

   ' Create a new SizeF object to return the size into

   Dim mySize As New System.Drawing.SizeF

 

   ' Create a new font based on the font of the textbox we want to resize

   Dim myFont As New System.Drawing.Font _

     (Me.TextBox1.Font.FontFamily, Me.TextBox1.Font.Size)

   '

   ' Or, use this for a specific font and font size.

   ' Dim myFont As New System.Drawing.Font("Verdana", 8)

 

   ' Get the size given the string and the font

   mySize = e.Graphics.MeasureString("This is a test", myFont)

 

   ' Resize the textbox to accommodate the entire string

   'Me.TextBox1.Width = mySize.Width

   Me.TextBox1.Width = CType(Math.Round(mySize.Width, 0), Integer)

 


Additional Resources

 

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.


View all FMS products for Microsoft Access All Our Microsoft Access Products

 

 

Free Product Catalog from FMS