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:
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):
using System;
using System.Windows.Forms;
namespace Custom_Controls
{
public class ExDataGrid: System.Windows.Forms.DataGrid
{
public void AutoResizeColumns()
{
if( !this.ColumnHeadersVisible )
return;
if(this.TableStyles.Count == 0)
return;
int x = this.RowHeaderWidth;
int y = 2;
if(this.CaptionVisible)
y = 23;
foreach(DataGridColumnStyle cstyle in
this.TableStyles[0].GridColumnStyles)
{
x += cstyle.Width + 1;
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.
Custom_Controls.ExDataGrid grid = new Custom_Controls.ExDataGrid();
grid.AutoResizeColumns();