Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Automatically resize datagrid column width

Posted on 2006-03-21
6
Medium Priority
?
4,160 Views
Last Modified: 2010-05-18
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)
0
Comment
Question by:preskh
6 Comments
 
LVL 10

Assisted Solution

by:123654789987
123654789987 earned 375 total points
ID: 16245170
U can refer the following article
http://support.microsoft.com/?id=812422
0
 
LVL 70

Assisted Solution

by:Éric Moreau
Éric Moreau earned 375 total points
ID: 16245833
0
 
LVL 4

Author Comment

by:preskh
ID: 16246216
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 28

Accepted Solution

by:
iboutchkine earned 375 total points
ID: 16246287
'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
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 16246335
>>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
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 375 total points
ID: 16247632
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

Featured Post

Technology Partners: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Loops Section Overview
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

580 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