0

Have datagridview, one column has wordwrap enabled. Setting AutoSizeRowsMode to anything other than None results in the grid taking a long time to populate. Doesn't matter if 10 rows or 100, bound or unbound. My grid is unbound. I would like to loop thru the row and based on the length of the text in the wrapped column calculate the row height for each row. How do I calculate the number of lines that have been produced by word-wrap? Or can I use the length of the text and based on other variables calculate the row height?

Other post suggest using DataGridViewAutoSizeRowsMode.DisplayedCells. That doesn't help.

Ricardo
  • 105
  • 1
  • 11
  • The Size of the text can be measure with [TextRenderer.MeasureText](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.textrenderer.measuretext). How is that going to help your case is undefined. Can you post the code that populates the grid? With a sample of the text. Or the average number of chars it contains and the Font your're using. – Jimi Jul 08 '19 at 22:48
  • https://stackoverflow.com/a/39667025/3110834 – Reza Aghaei Jul 09 '19 at 06:34
  • https://stackoverflow.com/a/52126967/3110834 – Reza Aghaei Jul 09 '19 at 06:35
  • Thanks for TextRender.MesaureIext idea and the links. I have it working exactly as I desired and there is is no loss of performance, This is how AutoSizeRowsMode should work. I loop and populate each cell of each row of the the grid and it surprisingly faster than binding. Here is my code to autosize each row. Hope it helps someone else. – Ricardo Jul 09 '19 at 15:31

2 Answers2

0
Dim strTemp As String
Dim szTemp As SizeF
Dim intLineHeight As Int32
Dim gphicsTemp As Graphics
gphicsTemp = Graphics.FromHwnd(Me.Handle)
Dim baselineSize As SizeF = gphicsTemp.MeasureString("SAMPLE ROW", dgvDeals.Font)
Dim intPadding As Int32 = 6
For Each dgvrTemp In dgvDeals.Rows
If dgvrTemp.Cells("CD_DESCRIPTION").Value.ToString.Trim <> "" Then
    strTemp = dgvrTemp.Cells("CD_DESCRIPTION").Value.ToString
    szTemp = gphicsTemp.MeasureString(strTemp, dgvDeals.Font, dgvrTemp.Cells("CD_DESCRIPTION").Size.Width)
    intLineHeight = Math.Round((szTemp.Height / baselineSize.Height))
    dgvrTemp.Height = (Math.Round(baselineSize.Height) * intLineHeight) + intPadding
End If
Next
Ricardo
  • 105
  • 1
  • 11
0

The easiest way is to use GetPreferredHeight:

For iRow As Int32 = 0 To dgvItems.Rows.Count - 1

    dgvItems.Rows(iRow).Height = 
dgvItems.Rows(iRow).GetPreferredHeight(iRow, DataGridViewAutoSizeRowMode.AllCells, True)

Next
NickCoder
  • 1,504
  • 2
  • 23
  • 35