• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 169
  • Last Modified:

DataGrid

Is there a way to programatically get the DtaaGrid in Visual Basic .NET 2003 to automatically resize its columns to fit the contents of the columns? Sort of like double-clicking in the vertical line separating the column headers.

Thanks
0
SETP
Asked:
SETP
  • 2
1 Solution
 
checooCommented:
One way to do this is to use MeasureString to compute the size of the text in each cell, and then take the maximum value. Below is a code snippet that does this. It assumes your datagrid is bound to a datatable.

Public Sub AutoSizeCol(col As Integer)
   Dim width As Single = 0
   Dim numRows As Integer = CType(dataGrid1.DataSource, DataTable).Rows.Count
   Dim g As Graphics = Graphics.FromHwnd(dataGrid1.Handle)
   Dim sf As New StringFormat(StringFormat.GenericTypographic)
   Dim size As SizeF  
   Dim i As Integer
   
   While i < numRows
      size = g.MeasureString(dataGrid1(i, col).ToString(), dataGrid1.Font, 500, sf)
      If size.Width > width Then
         width = size.Width
      End If
   End While
   g.Dispose()
 
   dataGrid1.TableStyles("customers").GridColumnStyles(col).Width = CInt(width) + 8 ' 8 is for leading and trailing padding
End Sub
0
 
Éric MoreauSenior .Net ConsultantCommented:
0
 
checooCommented:
yes but converted to VB.NET for my own project where I had a similar requirement
0
 
SETPAuthor Commented:
Thanks
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now