Determining the Width of Text

It’s not as hard as you might think in .NET. In the code below, just send the text and the Font object that, for example, the TextBox is using.

public static int GetTextWidth(string dataText, Font dataFont)
{
  return Graphics.FromImage(new Bitmap(1,1)).MeasureString(dataText, dataFont).ToSize().Width;
}

Tip Submitted By: David McCarter


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.