Lenght of a string

G

Guest

How can I measure the lenght of a text from a TextBox (in pixels) ?
I want to measure in KeyPress event the lenght of the text typed in a
textbox to put a listbox at the end of the text (something like IntelliSense).
I read about SizeF and MeasureString but I don't have a drawing object to
use in a textbox.
 
M

Marcos Stefanakopolus

There's probably a cleaner way, but at worst you do have access to the
TextBox's font information, and to it's Text property, so you could always
create a drawing object to draw the string into and go about using
MeasureString as before, only never bother to show the string to the user.
But doing it in place, I'm not sure. Maybe this is a case where the TextBox
control's CreateGraphics() method might be useful?
 
M

Morten Wennevik

Hi Sorin Sando,

You can create a graphics object using Control.CreateGraphics()
When creating a graphics object be sure to Dispose it when you
are finished using it.

TextBox t = new TextBox();
Graphics g = t.CreateGraphics();
SizeF s = g.MeasureString(t.Text, t.Font);
g.Dispose();

Note also that MeasureString doesn't give the exact size.
If you need exact size use MeasureCharacterRanges.
 
P

Peter Lillevold

Hi,
to be sure that the Graphics object is properly disposed, use a try/finally
clause
or even better, the using statement, like this:

TextBox t = new TextBox();
using (Graphics g = t.CreateGraphics())
{
SizeF s = g.MeasureString(t.Text, t.Font);
}

This will make sure that Dispose is called on g even in the case of an exception.

- Peter Lillevold
 
C

Carlos J. Quintero [.NET MVP]

Use the TextBox.CreateGraphics() method to get a System.Drawing.Graphics
object and use its MeasureCharacterRanges method (more exact than
MeasureString).

--

Carlos J. Quintero

MZ-Tools 4.0: Productivity add-ins for Visual Studio .NET
You can code, design and document much faster.
http://www.mztools.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top