kejpa Posted October 18, 2004 Posted October 18, 2004 Hi, more on the datagrid.... How do you set the width of a column to fit the content? If you double click between two columns the left column adjusts to the length of the longest item. I want that as the default width when I open the table. Can it be done? Of course, but help me out ;) TIA Kejpa Quote
Xanatos Posted April 27, 2005 Posted April 27, 2005 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 Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.