How to detect whether a winforms DataGridViewCell.Value is entirely visible in its cell?

StackOverflow https://stackoverflow.com/questions/16567285

  •  29-05-2022
  •  | 
  •  

Question

I'm looking for an easy way of identifying whether a WinForms DataGridViewCell.Value is entirely visible in its cell.

If the column is too narrow, only part of the value will be visible, and I need to detect that situation in code.

So far I'm thinking that I could compare the width of the content (with Graphics.MeasureString) with the width of the cell, but that seems a little clunky.

Looking for something a bit more elegant if possible.

Thanks

Était-ce utile?

La solution

From looking at the source code for DataGridViewCell, it looks like the .NET team decided to use the TextRenderer MeasureText function rather than the Graphics MeasureString function (see line 2924). It's not exactly what you were looking for, but it looks like it'd be a little less clunky then having to retrieve a Graphics object.

Beyond that, I do not believe there is a way to say for certain whether the Text cell is truncating a value or not. This probably has to do with performance. The DataGrid does not store a separate cell object for each cell... that would be far too memory intensive for large data sets. Rather, it stores style information as needed (usually for a whole column, though you can override the style data for a particular cell as necessary) and the the cell value (in a giant object array). When it comes time to render the cell, it reuses the same cell object for each cell in a column (calling Paint over and over with different cellBounds and value, etc.). Only during rendering would it know if the content is too long, but it throws this information away almost immediately (having nowhere to store it and no need for it after rendering).

I suppose the .NET team could have created a function to do all the measuring, etc., for you, but then again there are a lot of features that could have been implemented. This one wasn't.

Autres conseils

Just an idea ..

Function IsFit() as Boolean
  Dim szDummy As New SizeF

  dim picDummy as New Picturebox '--> or refer to your picbox
  gDummy = Me.picDummy.CreateGraphics
  szDummy = gDummy.MeasureString(column value , New Font(FontName, _
            FontSize, FontStyle, graphicUnitPixel))

  if szDummy.Width >= MyDataGrid.Columns(column name).Width then return True

End Function
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top