Hi,
I am trying to create a method that determines the width of a textbox in pixels based on the max length of a string.
The method takes a string and the font to be used by the textbox.
Before calling the method, I call some code that creates a string based on some user determined parameters, for example the user wants to set the box for 5 character, so I build a string with 5 zeros: "00000".
However whenever I use this method I manually enter the reqired number of zeros into the textbox, and the text never quite fits.
Looking around on MSDN, this seems a reasonable way of calculating the required length, but I cant quite get it to work.
Has anyone else attemted this method/ can they see where I am at fault or is there a betterway to do this as I am not too happy with basing it on a string oz Zeros.
private int FindStringWidth(string measurementString, Font f)
{
// Create a graphics object
System.Windows.Forms.
Control graphicsControl = null; Graphics measureGraphics = null; int width = 0; try{
graphicsControl = new System.Windows.Forms.Control();
measureGraphics = graphicsControl.CreateGraphics();
measureGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
// Create a StringFormat
StringFormat format = new StringFormat();format =
StringFormat.GenericTypographic;format.Trimming =
StringTrimming.None; // Create a rectangle and regionto hold the output size RectangleF rectangle = new RectangleF(0.0f, 0.0f, MaxWidthValue, MaxWidthValue); Region[] regions = new Region[1]; // Create a character range to measure CharacterRange[] ranges = { new CharacterRange(0, measurementString.Length) };format.SetMeasurableCharacterRanges(ranges);
// Measure the stringregions = measureGraphics.MeasureCharacterRanges(measurementString, f, rectangle, format);
rectangle = regions[0].GetBounds(measureGraphics);
width = (
int)(rectangle.Width + 0.5f);}
finally
{
// Clean up the Graphics object.measureGraphics.Dispose();
graphicsControl.Dispose();
}
// Return the string length
return width;}
Thank you,
Kenny