Option 1 - Overriding GetPreferredSize
You can override GetPreferredSize
method of DataGridView
and call the base method using new proposed size new Size(this.Width, proposedSize.Height)
. This way, the current width of control will remain untouched while the auto-size rules will apply on its height:
using System.Drawing;
using System.Windows.Forms;
public class MyDataGridView : DataGridView
{
public override Size GetPreferredSize(Size proposedSize)
{
return base.GetPreferredSize(new Size(this.Width, proposedSize.Height));
}
}
Option 2 - Setting the Height based on Height of Calculated Auto-Size
If you don't want to derive from DataGridView
, you can calculate the auto-size by calling its GetPreferredSize
passing new Size(0, 0)
then set the height of DataGridView
to the height of result, this way you only change the height of DataGridView
. You should set the auto-height in RowsAdded
, RowsRemoved
, some other events if you need:
void AutoHeightGrid(DataGridView grid)
{
var proposedSize = grid.GetPreferredSize(new Size(0, 0));
grid.Height = proposedSize.Height;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.RowsAdded += (obj, arg) => AutoHeightGrid(dataGridView1);
dataGridView1.RowsRemoved += (obj, arg) => AutoHeightGrid(dataGridView1);
//Set data source
//dataGridView1.DataSource = something;
}
If you want to make sure that all changes in grid including changing Font
, height of rows will cause resizing grid, you can call the method in Paint
event.
Option 3 - Setting MaximumSize
Also as mentioned by Hans, if you don't want to derive from DataGridView
, you can use MaximumSize
property of the grid. You can set it to new Size(this.dataGridView1.Width, 0)
:
dataGridView1.MaximumSize = new Size(this.dataGridView1.Width, 0);
dataGridView1.AutoSize = true;
Note
Since using MaximumSize
is not so friendly when the user wants to let the grid width change by left and right anchors, I prefer to use Option 1 or Option 2.