Display wide/narrow captions in DataGridView

severtki

New member
Joined
Aug 17, 2007
Messages
2
Programming Experience
10+
How to measure text width of a string?

I'd like to display narrow or wide captions for column headers in a DataGridView, depending on the user-selected width of the column. For example, I'd display "Account Number" if there were room for it, otherwise "Acct Num". If the user resizes the column, I'd like to redisplay the appropriate caption.

It looks like there's a MeasureTextWidth function of DataGridViewCell, (requires that I pass it a Graphics). How do I obtain a graphics object? There's no Graphics passed in eventargs to ColumnWidthChanged event (the logical place to set the caption), and I create a new one using New System.Drawing.Graphics -- error no constructor defined:

Dim l As Integer = DataGridViewCell.MeasureTextWidth(New System.Drawing.Graphics, "Account Number", grid.ColumnHeadersDefaultCellStyle.Font, grid.ColumnHeadersHeight, TextFormatFlags.Default)


I know I could grab the Graphics parameter from eventargs in CellPainting event, but then I'd have to handle the actual painting of it myself. Am I missing something obvious?

Thanks in advance.
 
CreateGraphics method of the DataGridView is probably good in this case, remember to dispose it after use.
 
Back
Top