Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C#
Article

Resizing Datagrid Columns to content, keeping the table styles

Rate me:
Please Sign up or sign in to vote.
4.14/5 (5 votes)
28 May 20051 min read 90.1K   855   36   12
This simple function resizes all columns in a DataGrid to its contents, without losing table styles.

Introduction

In my quest to find an easy way to resize columns of a Datagrid object to its contents, I found an article right here at The Code Project by Tom Archer which should do just that. His code however erases all defined TableStyles that might have been added to the grid and makes a new one with recalculated widths of the ColumnStyles to fit the content. But all my grids have TableStyles (and ColumnStyles) defined, so this code didn't do it for me and my quest went on.

Solution

Ever tried to click just between two columns of a DataGrid? Right! The columns resize themselves to fit their content. Just the kind of behaviour I was looking for. So, why implement this behaviour, but not make this method public?

By extending the DataGrid class and adding a function to this extended class, I call the protected OnMouseDown method of the Datagrid class like this:

C#
this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 2, x--, y, 0));

The parameter values I pass on to the MouseEventArgs constructor are:

  • the left mouse button is pressed,
  • twice (i.e., double click),
  • an x coordinate representing a coordinate right between two columns,
  • a y coordinate representing the coordinates of the column headers,
  • a zero Delta value (nudges of the mouse wheel, don't apply here for obvious reasons).

This call simulates a double click event at specific coordinates (namely between two columns headers).

Using the code

The complete code I wrote looks like this (this is an extension to the DataGrid class):

C#
using System;
using System.Windows.Forms;

namespace Custom_Controls
{
    public class ExDataGrid: System.Windows.Forms.DataGrid
    {

        public void AutoResizeColumns()
        {
            //If the columnheaders aren't visible this code doesn't work...
            if( !this.ColumnHeadersVisible )
                return;

            //If there are no TableStyles defined, exit. Use Tom Archer's code.
            if(this.TableStyles.Count == 0)
                return;

            
            //This is the width of rowheaders 
            //(the part of the grid in front of each row)
            int x = this.RowHeaderWidth;
            int y = 2;
            //If the Caption is visible, the columnheaders 
            //are a bit below, so make y 23.
            if(this.CaptionVisible)
                y = 23;
            foreach(DataGridColumnStyle cstyle in 
                    this.TableStyles[0].GridColumnStyles)
            {
                //the y coordinate is already set, and doesn't change
                x += cstyle.Width + 1;
                //so adjust each time the x coordinate 
                //so the x,y coordinates represent a 
                //point between two columns
                
                //then fake a double click at that 
                //exact spot. -> the columns will resize.
                this.OnMouseDown(new MouseEventArgs(
                    MouseButtons.Left, 2, x--, y, 0));
            }
        }
    }
}

So to use this code, simply add an instance of the ExDataGrid (instead of the normal DataGrid) to your forms, and call this AutoResizeColumns() function.

C#
Custom_Controls.ExDataGrid grid = new Custom_Controls.ExDataGrid();
grid.AutoResizeColumns();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalaccessing the records through column Pin
kris_bgp3-Jul-06 0:40
kris_bgp3-Jul-06 0:40 
GeneralDo Not Works With Hidden Columns. Pin
georani1-Jun-05 0:34
georani1-Jun-05 0:34 
GeneralRe: Do Not Works With Hidden Columns. Pin
Anonymous1-Jun-05 1:10
Anonymous1-Jun-05 1:10 
GeneralAn alternative approach Pin
Rob Lans30-May-05 1:59
Rob Lans30-May-05 1:59 
GeneralRe: An alternative approach Pin
Tijz1-Jun-05 1:15
Tijz1-Jun-05 1:15 
GeneralRe: An alternative approach Pin
Tijz1-Jun-05 2:35
Tijz1-Jun-05 2:35 
GeneralRe: An alternative approach (Don't works too) Pin
georani2-Jun-05 0:57
georani2-Jun-05 0:57 
GeneralRe: An alternative approach (Don't works too) Pin
Reinier Beeckman5-Jun-05 21:35
Reinier Beeckman5-Jun-05 21:35 
GeneralRe: An alternative approach (Don't works too) Pin
Member 19715476-Jun-05 18:32
Member 19715476-Jun-05 18:32 
GeneralRe: An alternative approach (Don't works too) Pin
Simon Soosai9-Jun-05 8:19
Simon Soosai9-Jun-05 8:19 
GeneralRe: An alternative approach (Don't works too) Pin
vrx411-Jun-05 19:36
vrx411-Jun-05 19:36 
GeneralRe: An alternative approach (Don't works too) Pin
HerbCSO24-Sep-05 2:15
HerbCSO24-Sep-05 2:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.