Click here to Skip to main content
11,790,021 members (50,366 online)
Click here to Skip to main content

Resizing Data Grid Columns To Content

, 17 Mar 2003 165.6K 3.6K 68
Rate this:
Please Sign up or sign in to vote.
Method that resizes all the columns of a specified Data Grid object
<!-- Article image -->

Sample Image - SizeColumnsToContent.jpg


One peculiar omission from the Windows Forms teams regarding the DataGrid object is a method that enables you to resize the grid's columns to visually accomodate the width of its widest data value. This method gives you that ability.


While searching for a solution to this problem, a friend emailed me some Visual Basic.NET code to accomplish the feat. While I could not get the code to compile (I'm assuming it was written during one of the .NET betas), I did re-write it in C# and got it to work. I'll update this article to give a proper acknowledgment, once I track down the original author's name. However, I did want to make clear that some kind soul did get me 90% of the way there, with their VB code and I finished the rest for my C# environment.

Using the code


Calling this method is very straightforward. It takes only two parameters:

public void SizeColumnsToContent(DataGrid dataGrid, int nRowsToScan) 
  • dataGrid - The DataGrid object to be resized
  • nRowsToScan - The number of rows to scan, when searching for the widest value for a given column. Passing a value of -1 indicates that all rows should be scanned.


  • In my own code, I have defined this method as a member of my own System.Windows.Forms.DataGrid-derived class (DataGridEx). I removed it from that class for this article, in order to keep things simple. To use the method in the same manner that I did, simply remove the dataGrid parameter from the parameter list and replace the references to dataGrid with reference to the this object.

  • The reason for the nRowsToScan parameter is for performance issues regarding very large amounts of data. If you happen to have a datagrid with a large number of rows, you can simply have the grid's columns sized according to the widest column of the first n rows instead of the method iterating through the entire data set for each column.

SizeColumnsToContent Method

public void SizeColumnsToContent(DataGrid dataGrid, int nRowsToScan) 
    // Create graphics object for measuring widths.
    Graphics Graphics = dataGrid.CreateGraphics();

    // Define new table style.
    DataGridTableStyle tableStyle = new DataGridTableStyle();

        DataTable dataTable = (DataTable)dataGrid.DataSource;
        if (-1 == nRowsToScan)
            nRowsToScan = dataTable.Rows.Count;
            // Can only scan rows if they exist.
            nRowsToScan = System.Math.Min(nRowsToScan, 
        // Clear any existing table styles.
        // Use mapping name that is defined in the data source.
        tableStyle.MappingName = dataTable.TableName;
        // Now create the column styles within the table style.
        DataGridTextBoxColumn columnStyle;
        int iWidth;
        for (int iCurrCol = 0; iCurrCol < dataTable.Columns.Count; 
            DataColumn dataColumn = dataTable.Columns[iCurrCol];
            columnStyle = new DataGridTextBoxColumn();

            columnStyle.TextBox.Enabled = true;
            columnStyle.HeaderText = dataColumn.ColumnName;
            columnStyle.MappingName = dataColumn.ColumnName;
            // Set width to header text width.
            iWidth = (int)(Graphics.MeasureString(columnStyle.HeaderText, 

            // Change width, if data width is wider than header text width.
            // Check the width of the data in the first X rows.
            DataRow dataRow;
            for (int iRow = 0; iRow < nRowsToScan; iRow++)
                dataRow = dataTable.Rows[iRow];
                if (null != dataRow[dataColumn.ColumnName])
                    int iColWidth = (int)(Graphics.MeasureString(dataRow.
                    iWidth = (int)System.Math.Max(iWidth, iColWidth);
            columnStyle.Width = iWidth + 4;
            // Add the new column style to the table style.
        // Add the new table style to the data grid.
    catch(Exception e)


  • March 18, 2003 - First posting


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


About the Author

Tom Archer
Software Developer (Senior) Microsoft
United States United States
I'm a Senior Programming Writer in the Microsoft Windows Server organization where my focus is WMI, BITS, WinRM, and SMI-S.

You may also be interested in...

Comments and Discussions

GeneralWell.. Pin
Muammar©25-Sep-07 0:57
memberMuammar©25-Sep-07 0:57 
GeneralThanx Pin
niljag21009-Jun-06 0:39
memberniljag21009-Jun-06 0:39 
GeneralPocket Pc trouble Pin
Lacran1-Jun-06 5:28
memberLacran1-Jun-06 5:28 
GeneralStyles Pin
recursion_man25-Apr-06 9:19
memberrecursion_man25-Apr-06 9:19 
GeneralA few modifications Pin
sixgun15-Feb-06 5:28
membersixgun15-Feb-06 5:28 
GeneralRe: A few modifications Pin
emreo16-Feb-06 4:15
memberemreo16-Feb-06 4:15 
GeneralRe: A few modifications Pin
sixgun16-Feb-06 4:36
membersixgun16-Feb-06 4:36 
GeneralWorks like a charm! Pin
ajrulez10-Dec-05 12:36
memberajrulez10-Dec-05 12:36 
GeneralBit Fields Pin
vrosso12-Oct-05 2:52
membervrosso12-Oct-05 2:52 
General5693Multiline DataGrid Header Text Pin
shanu523811-Apr-05 1:56
sussshanu523811-Apr-05 1:56 
GeneralRe: 5693Multiline DataGrid Header Text Pin
wws3580123-Jun-05 8:40
memberwws3580123-Jun-05 8:40 
Generalwant to use it for WebApplication Pin
weinklein25-Jan-05 1:33
memberweinklein25-Jan-05 1:33 
GeneralRe: want to use it for WebApplication Pin
Tom Archer25-Jan-05 1:49
memberTom Archer25-Jan-05 1:49 
GeneralPlease help, overwriting my config Pin
OnlineNoob12-Jan-04 13:26
memberOnlineNoob12-Jan-04 13:26 
GeneralRe: Please help, overwriting my config Pin
DruZeree10-Mar-04 10:42
memberDruZeree10-Mar-04 10:42 
GeneralRe: Please help, overwriting my config Pin
<a href=''>coderforrent3-May-04 11:00
membercoderforrent3-May-04 11:00 
GeneralExtension proposal Pin
ThaNerd30-Nov-03 5:23
memberThaNerd30-Nov-03 5:23 
Generalgood source Pin
SEUNG-PIL YOO19-Nov-03 18:40
memberSEUNG-PIL YOO19-Nov-03 18:40 
GeneralRe: good source Pin
developer199623-Dec-03 6:20
memberdeveloper199623-Dec-03 6:20 
Generalplease help cast error Pin
Sashka2-Sep-03 6:47
memberSashka2-Sep-03 6:47 
GeneralRe: please help cast error Pin
KhSergey6-Sep-03 13:19
memberKhSergey6-Sep-03 13:19 
GeneralRe: please help cast error Pin
Sashka7-Sep-03 5:36
memberSashka7-Sep-03 5:36 
GeneralRe: please help cast error Pin
Darrell Merrick1-Oct-03 13:57
sussDarrell Merrick1-Oct-03 13:57 
GeneralRe: please help cast error Pin
Boogie7-Nov-03 12:26
memberBoogie7-Nov-03 12:26 
GeneralRe: please help cast error Pin
Tom Archer7-Sep-03 12:48
memberTom Archer7-Sep-03 12:48 
Generallittle problem Pin
SevviP20-Jul-03 21:18
memberSevviP20-Jul-03 21:18 
GeneralRe: little problem Pin
Tom Archer21-Jul-03 4:46
memberTom Archer21-Jul-03 4:46 
GeneralRe: little problem Pin
Vinny Rosso23-Sep-03 2:43
memberVinny Rosso23-Sep-03 2:43 
GeneralRe: little problem Pin
Tom Archer23-Sep-03 3:31
memberTom Archer23-Sep-03 3:31 
GeneralRe: little problem Pin
jason@myveryownwebsite.com21-Dec-03 16:17
memberjason@myveryownwebsite.com21-Dec-03 16:17 
GeneralRe: little problem Pin
Fred Hommel13-Nov-03 8:59
memberFred Hommel13-Nov-03 8:59 
GeneralI just wonder... Pin
treborg18-Jun-03 1:26
membertreborg18-Jun-03 1:26 
GeneralHere is the code in VB.NET Pin
Oliver Degnan24-Mar-03 8:34
sussOliver Degnan24-Mar-03 8:34 
GeneralRe: Here is the code in VB.NET Pin
dazmiller11-Apr-03 23:29
memberdazmiller11-Apr-03 23:29 
GeneralRe: Here is the code in VB.NET Pin
Pablo Robert8-Mar-05 10:18
memberPablo Robert8-Mar-05 10:18 
GeneralRe: Here is the code in VB.NET (shows boolean cols as checkboxes) Pin
Jay Ayliff15-Jun-05 21:18
memberJay Ayliff15-Jun-05 21:18 
GeneralThanks Pin
Sijin20-Mar-03 18:49
memberSijin20-Mar-03 18:49 
GeneralRe: Thanks Pin
Tom Archer20-Mar-03 22:11
memberTom Archer20-Mar-03 22:11 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1509028.1 | Last Updated 18 Mar 2003
Article Copyright 2003 by Tom Archer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid