Grid column width

V

venky

HI guys,

In one of my columns in the grid, i want to set the width of the grid
to the widest entry in the column when i click on the column seperator.
How can i calcualte the column width if i know the lenght of the
longest string?
 
N

Nicholas Paldino [.NET/C# MVP]

venky,

If you know the font that the column is being rendered in, and the text,
you can use the MeasureString method on the Graphics class to get the width
of the longest element.

Using this method to calculate the length of the longest string will not
give you the longest ^rendered^ string. Unless you are using a fixed-width
font (which I assume you are not), you will have to pass every string to
this method, with the Font, and then get the max length.

For example, say you have a string composed of 20 'i' characters and a
string with 20 'W' characters. The one composed of 'W' is going to be
longer, even though the length of the string in characters is the same.

You can get the Graphics instance by passing the handle of the grid to
the static FromWnd method on the Graphics class.

Hope this helps.
 

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