Public Sub AutoSizeDataGridColumns(ByVal dgData As DataGrid, ByVal strMappingName As String, ByVal intPadding As Integer)
Dim ex1 As New Exception("DataGrid must be databound")
Dim ex2 As New Exception("DataSource must be DataSet or DataTable")
Dim ex3 As New Exception("Invalid tablename in the DataSet")
Dim dt As DataTable
Dim dr As DataRow
Dim dset As New DataSet
Dim dcCol As DataColumn
Dim gr As Graphics
Dim sngGridNameWidth, sngDataWidth As Single
Dim i As Integer, sngPadding As Single
Dim ts As New DataGridTableStyle ' Create a new table style
ts.MappingName = strMappingName ' Address the TableGrid Style
If dgData.TableStyles.Contains(ts.MappingName) = False Then dgData.TableStyles.Add(ts) ' Attach the new style if the table does not have this style
If dgData.DataSource Is Nothing Then
Throw ex1
Exit Sub
End If
If TypeOf dgData.DataSource Is DataSet Then
dset = dgData.DataSource
dt = dset.Tables(dgData.DataMember)
ElseIf TypeOf dgData.DataSource Is DataTable Then
dt = dgData.DataSource
Else
Throw ex2
Exit Sub
End If
If dt.Rows.Count > 0 Then ' Don't change size if there are no rows.
Try
dgData.BeginInit()
dr = dt.Rows(0)
Dim sz As SizeF 'Stores an ordered pair of floating-point numbers, typically the width and height of a rectangle.
gr = dgData.CreateGraphics
sz = gr.MeasureString(New String("M", intPadding), dgData.Font) ' Pad "n" M-width characters
sngPadding = sz.Width
For Each dcCol In dt.Columns ' Loop through the column header
' Measure the "width" of the text in each grid column header
Try
sz = gr.MeasureString(dgData.TableStyles(ts.MappingName).GridColumnStyles(dcCol.Ordinal).HeaderText, dgData.Font)
dgData.TableStyles(ts.MappingName).GridColumnStyles(dcCol.Ordinal).Width = sz.Width + sngPadding
Catch ex As ArgumentOutOfRangeException
Throw ex3
End Try
Next ' dcCol loop through each column in the bound DataTable
For i = 0 To dgData.VisibleRowCount - 2 ' Calculate width on all visible rows (header row counted)
For Each dcCol In dt.Columns ' Loop through each column
dr = dt.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(dcCol.Ordinal).ToString, dgData.Font) ' Measure "width" of data value
dgData.TableStyles(0).GridColumnStyles(dcCol.Ordinal).Width = _
Math.Max(sz.Width + sngPadding, _
dgData.TableStyles(0).GridColumnStyles(dcCol.Ordinal).Width) ' Use larger width
Next ' Next DataGrid Column
Next i ' Next DataRow
Catch ex As Exception
MsgBox(ex.ToString)
Finally
dgData.EndInit() ' complete graphics edit
gr.Dispose() ' Release graphic object
End Try
ts.AllowSorting = False
ts.ReadOnly = True
End If ' Test for DataTable Rows
End Sub