Hi,
Read this:
http://windowsforms.net/articles/gdiptext.aspx
Cheers
Doug Forster
"MrNobody" <MrNobody@discussions.microsoft.com> wrote in message
news:A331942F-3FC6-470F-8708-0830A21928A5@microsoft.com...[color=blue]
> Err, sorry when I editted the post I must have deleted all mention of the
> fact I use a monospace font- namely Courier New. Otherwise I wouldn't have
> even tried it this way.
>
> Using Courier New, I did a test and found it was getting the same font
> width
> regardless of the character (like lowercase 'L' same width as underscore
> '_')
> but this number seems to be too wide, because when I multiply this number
> by
> the number of characters and apply it to my DataGrid, the columns end up
> too
> wide
>
> "Les" wrote:
>[color=green]
>> You cannot use the width of an arbitrary character becasue you don't have
>> fixed width characters. If you use a fixed width font, then your
>> solution
>> will work, but with most of the fonts the letters are varying widths and
>> so
>> you will not have a true length unless you sum the width of each
>> character.
>>
>> "MrNobody" wrote:
>>[color=darkred]
>> > I am trying to make a method that will autosize columns to fit the
>> > longest
>> > text contained in a DataGrid.
>> >
>> > My plan was to take the width of an arbitrary character (underscore, in
>> > this
>> > case) and multiply this width to the longest # of characters found for
>> > each
>> > column.
>> >
>> > But it comes out wrong... I find the longest string no problem, but
>> > when I
>> > multiply it by the width that I measured for a single character, it
>> > comes out
>> > too big... the columns in the datagrid then get stretched out too
>> > wide,
>> > instead of just snug like I wanted. What gives?
>> >
>> > Font font = datagrid.Font;
>> > float fontWidth = g.MeasureString("_", font).Width;
>> >
>> > // find longest strings in each of datagrid's columns
>> > ...
>> >
>> > // change column style's width to product of longest string length and
>> > font
>> > width
>> > styles[x].Width = (int)(max_widths[x] * fontWidth);
>> >[/color][/color][/color]