Public Shared Sub GridAutoSize(ByVal ds As DataSet, ByVal dg As DataGrid, ByVal dgName As String)
dg.DataSource = ds.Tables(0)
dg.Expand(-1)
dg.NavigateTo(0, dgName)
Dim gr As Graphics
gr = dg.CreateGraphics
Dim intPadding As Integer = 5
Dim sz As SizeF
'sz = gr.MeasureString(New String("M", intPadding), dg.Font)
Dim gridStyle As New DataGridTableStyle
gridStyle.MappingName = dgName
gridStyle.AlternatingBackColor = GridUtility.AlternatingBackColor
gridStyle.BackColor = GridUtility.BackColor
gridStyle.SelectionBackColor = GridUtility.SelectedBackColor
Dim t As New DataGrid
If (dg.TableStyles.Contains(dgName)) Then
dg.TableStyles.RemoveAt(0)
End If
If (ds.Tables.Count > 0) Then
Dim col As DataColumn
For Each col In ds.Tables.Item(dgName).Columns
Dim dgCol As New DataGridTextBoxColumn
Dim colCount As Integer
colCount = ds.Tables.Item(dgName).Columns.Count()
sz = gr.MeasureString(col.ColumnName, dg.Font)
dgCol.MappingName = col.ColumnName
dgCol.HeaderText = col.ColumnName
dgCol.Width = sz.Width + 15
dgCol.Alignment = HorizontalAlignment.Left
dgCol.TextBox.Enabled = False
gridStyle.GridColumnStyles.Add(dgCol)
Next
If (ds.Tables.Item(dgName).Rows.Count > 0) Then
Dim dr As DataRow
Dim dtCol As DataColumnCollection
dtCol = ds.Tables.Item(dgName).Columns
Dim i As Integer
i = dg.VisibleRowCount
For i = 0 To dg.VisibleRowCount - 2 ' Calculate width on all visible rows (header row counted)
For Each col In dtCol
' Loop through each column
dr = ds.Tables.Item(dgName).Rows(i) ' Navigate to visible rows
' Measure the "width" of the txt in the first row of each bound DataTable column
sz = gr.MeasureString(dr(col.ColumnName).ToString, dg.Font) ' Measure "width" of data value
gridStyle.GridColumnStyles(col.ColumnName).Width = _
Math.Max(sz.Width + intPadding, gridStyle.GridColumnStyles(col.ColumnName).Width)
Next ' Next DataGrid Column
Next i ' Next DataRow
dg.TableStyles.Add(gridStyle)
End If
End If
End Sub