Automatically resize datagrid column width

How to automatically resize a datgrid's column width to the length of the longest item in a column. How to apply it to this code ?

Dim dTable As New DataTable

dTable.Columns.Add("Name")
dTable.Columns.Add("Information")
Dim myDatatView As New DataView(dTable)
DataGrid1.DataSource = myDatatView

Dim dRow As DataRow

dRow = dTable.NewRow
dRow(0) = "aa"
dRow(1) = "bb"
dTable.Rows.Add(dRow)

dRow = dTable.NewRow
dRow(0) = "123aaaaaaaaaaaaaaaaaaaaa456"
dRow(1) = "123bbbbbbbb456"
dTable.Rows.Add(dRow)
LVL 4
preskhAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

123654789987Commented:
U can refer the following article
http://support.microsoft.com/?id=812422
0
Éric MoreauSenior .Net ConsultantCommented:
0
preskhAuthor Commented:
I have already seen the microsoft article and some datagrid resizing questions in experts-exchange. But I am not sure how to apply that to this case where data in rows are manually added through code.

emoreau I converted the VB 6 code given in your link to VB .Net code and I get this error in the "numRows = CType(dataGrid1.DataSource, DataTable).Rows.Count" line

An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication1.exe

Additional information: Specified cast is not valid.

Also should I change the 'customers' in the line "dataGrid1.TableStyles("customers").GridColumnStyles(col).Width = CType(width, Integer)" to 'Name'(Name and Information are the column headings in my code)
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

iboutchkineCommented:
'1.Create Form1 and replace the whole code with the following code.
'It will create Datagrid dg, Label lblCol, textbox txtCol and button btnAutoSize
'2. Replace TesDb database to your database and table PRQ to your table
'3.Modify TableStyle section (ts) of the code to get your fields
'4.Run the code"
'enter the col number ot the textbox to resize or leave txtbox blank to resize all

Imports System.Data.OleDb

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents btnAutoSize As System.Windows.Forms.Button
    Friend WithEvents dg As System.Windows.Forms.DataGrid
    Friend WithEvents lblCol As System.Windows.Forms.Label
    Friend WithEvents txtCol As System.Windows.Forms.TextBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.btnAutoSize = New System.Windows.Forms.Button
        Me.dg = New System.Windows.Forms.DataGrid
        Me.lblCol = New System.Windows.Forms.Label
        Me.txtCol = New System.Windows.Forms.TextBox
        CType(Me.dg, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'btnAutoSize
        '
        Me.btnAutoSize.Location = New System.Drawing.Point(232, 168)
        Me.btnAutoSize.Name = "btnAutoSize"
        Me.btnAutoSize.TabIndex = 12
        Me.btnAutoSize.Text = "AutoSize"
        '
        'dg
        '
        Me.dg.DataMember = ""
        Me.dg.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dg.Location = New System.Drawing.Point(4, 4)
        Me.dg.Name = "dg"
        Me.dg.Size = New System.Drawing.Size(520, 152)
        Me.dg.TabIndex = 11
        '
        'lblCol
        '
        Me.lblCol.Location = New System.Drawing.Point(8, 164)
        Me.lblCol.Name = "lblCol"
        Me.lblCol.Size = New System.Drawing.Size(128, 32)
        Me.lblCol.TabIndex = 13
        Me.lblCol.Text = "EnterColon # to resize or leave blank for all"
        '
        'txtCol
        '
        Me.txtCol.Location = New System.Drawing.Point(144, 168)
        Me.txtCol.Name = "txtCol"
        Me.txtCol.Size = New System.Drawing.Size(68, 20)
        Me.txtCol.TabIndex = 14
        Me.txtCol.Text = ""
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(524, 214)
        Me.Controls.Add(Me.txtCol)
        Me.Controls.Add(Me.lblCol)
        Me.Controls.Add(Me.btnAutoSize)
        Me.Controls.Add(Me.dg)
        Me.Name = "Form1"
        Me.Text = "Form1"
        CType(Me.dg, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region
    Private Const DBNAME = "c:\testdb\testdb.mdb"
    Dim sConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & DBNAME & _
                          ";Persist Security Info=False"
    Private ds As New DataSet
    Private da As New OleDbDataAdapter("select YYYYMM, ProdID, Name from PRQ", sConn)
    Dim cmdBuilder As New OleDbCommandBuilder(da)

    Dim cn As OleDbConnection


    Dim c As DataGridTextBoxColumn
    Dim ts As DataGridTableStyle


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim c As DataGridTextBoxColumn
        Dim ts As DataGridTableStyle

        da.Fill(ds, "PRQ")
        dg.DataSource = ds
        dg.DataMember = "PRQ"
        ts = New DataGridTableStyle
        ts.MappingName = "PRQ"
        c = New DataGridTextBoxColumn
        c.MappingName = "YYYYMM"
        c.Width = 50
        c.HeaderText = "YYYYMM"
        c.Alignment = HorizontalAlignment.Left '(Right Or center)
        ts.GridColumnStyles.Add(c)

        c = New DataGridTextBoxColumn
        c.MappingName = "ProdID"
        c.Width = 50
        c.HeaderText = "Prod ID"
        ts.GridColumnStyles.Add(c)

        c = New DataGridTextBoxColumn
        c.MappingName = "Name"
        c.Width = 200
        c.HeaderText = "Prod Name"
        ts.GridColumnStyles.Add(c)
        dg.TableStyles.Add(ts)


    End Sub
    Private Sub btnAutoSize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAutoSize.Click
        If txtCol.Text.Length = 0 Then
            AutoSizeTable() 'autosize all cols
        Else
            AutoSizeCol(CType(txtCol.Text, Integer)) 'autosize  col in brackets
        End If
    End Sub
    Public Sub AutoSizeTable()
        Dim numCols As Integer
        numCols = ds.Tables("PRQ").Columns.Count

        Dim i As Integer
        i = 0
        Do While (i < numCols)
            AutoSizeCol(i)
            i = (i + 1)
        Loop

    End Sub

    Public Sub AutoSizeCol(ByVal col As Integer)

        Dim width As Single
        width = 0
        Dim numRows As Integer
        numRows = ds.Tables("PRQ").Columns.Count
        Dim g As Graphics
        g = Graphics.FromHwnd(dg.Handle)
        Dim sf As StringFormat
        sf = New StringFormat(StringFormat.GenericTypographic)
        Dim size As SizeF
        Dim i As Integer
        i = 0

        Do While (i < numRows)
            size = g.MeasureString(dg(i, col).ToString, dg.Font, 500, sf)
            If (size.Width > width) Then
                width = size.Width
            End If
            i = (i + 1)

        Loop
        g.Dispose()
        'dg.TableStyles("PRQ").GridColumnStyles(col).Width = CType(width, Integer)

        dg.TableStyles("PRQ").GridColumnStyles(col).Width = width
    End Sub
End Class
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Éric MoreauSenior .Net ConsultantCommented:
>>emoreau I converted the VB 6 code given in your link to VB .Net code

It is surely not VB6! It is C#. You can download the VB.Net equivalent using the "VB" link at the end of the description.


>>and I get this error in the "numRows = CType(dataGrid1.DataSource, DataTable).Rows.Count" line
>>An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication1.exe

What is your DataSource set to? If if is a DataView, then you have to cast it as a DataView instead of a DataTable.
0
Bob LearnedCommented:
If you are using a DataGrid table style, then you can define the column widths as a percentage of the windows ClientSize.Width:

column.Width = Me.ClientSize.Width * .3

Bob
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.