Autosizing delle righe di un DataGrid

A volte mi capita di dover mettere mano a codice .NET 1.1 su Visual Studio 2003 e in questa versione la griglia nativa il DataGrid non era ricco di funzionalità. L’ultima richiesta che mi è arrivata è come realizzare l’autosizing delle righe per vedere completamente il contenuto delle righe le cui colonne vano su più righe. Manualment la cosa è possibiole quindi la funzionalità in effetti c’è ma non è esposta e quindi occorre utilizzare la reflection come indicato in questo link http://www.syncfusion.com/FAQ/winforms/FAQ_c44c.aspx

Di seguito la versione che ho realizzato:

Private Sub AutoSizeRows(ByVal columnStyle As System.Windows.Forms.DataGridColumnStyle)
  Dim dataGrid As System.Windows.Forms.DataGrid = columnStyle.DataGridTableStyle.DataGrid
  Dim dataGridtype As System.Type = dataGrid.GetType

  Do
    dataGridtype = dataGridtype.BaseType
    If dataGridtype Is Nothing Then Exit Sub
  Loop Until dataGridtype.FullName = GetType(System.Windows.Forms.DataGrid).FullName
 
  While dataGridtype.FullName <> GetType(System.Windows.Forms.DataGrid).FullName
    dataGridtype = dataGridtype.BaseType
  End While

  Dim mi As System.Reflection.MethodInfo = dataGridtype.GetMethod(“get_DataGridRows”, _
    Reflection.BindingFlags.FlattenHierarchy Or _
    Reflection.BindingFlags.IgnoreCase Or _
    Reflection.BindingFlags.Instance Or _
    Reflection.BindingFlags.NonPublic Or _
    Reflection.BindingFlags.Public Or _
    Reflection.BindingFlags.Static)

  Dim dataGridRows As New ArrayList

  For Each item As Object In CType(mi.Invoke(dataGrid, Nothing), Array)
    If item.ToString().EndsWith(“DataGridRelationshipRow”) Then
      dataGridRows.Add(item)
    End If
  Next

  Dim bmb As System.Windows.Forms.BindingManagerBase = _
    dataGrid.BindingContext(dataGrid.DataSource, dataGrid.DataMember)

  If Not bmb Is Nothing AndAlso bmb.Count > 0 Then
    Dim size As System.Drawing.SizeF
    Dim g As System.Drawing.Graphics = _
      System.Drawing.Graphics.FromHwnd(dataGrid.Handle)
    Dim sf As New StringFormat(StringFormat.GenericTypographic)
    Dim columnIndex As Integer = columnStyle.DataGridTableStyle.GridColumnStyles.IndexOf(columnStyle)
    Dim pi As System.Reflection.PropertyInfo
    Dim rowHeight As Integer

    For rowIndex As Integer = 0 To bmb.Count – 1
      size = g.MeasureString(dataGrid(rowIndex, columnIndex).ToString(), dataGrid.Font, columnStyle.Width, sf)
      pi = dataGridRows(rowIndex).GetType().GetProperty(“Height”)
      rowHeight = System.Convert.ToInt32(size.Height)

      ‘Little extra cellpadding space
      rowHeight += 8

      pi.SetValue(dataGridRows(rowIndex), rowHeight, Nothing)
    Next

    ‘Rilascio risorse
     g.Dispose() : g = Nothing
     sf.Dispose() : sf = Nothing
  End If
End Sub