Posted on 2005-05-12
Last Modified: 2010-04-23
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.

Question by:SETP
    LVL 9

    Accepted Solution

    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
       dataGrid1.TableStyles("customers").GridColumnStyles(col).Width = CInt(width) + 8 ' 8 is for leading and trailing padding
    End Sub
    LVL 69

    Expert Comment

    by:Éric Moreau
    LVL 9

    Expert Comment

    yes but converted to VB.NET for my own project where I had a similar requirement

    Author Comment


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Article by: jpaulino
    XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String ( Literal, only instead of starting and ending with w…
    If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.
    This video discusses moving either the default database or any database to a new volume.

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now