winforms: datagridview: height (autosize) depending on number of rows

ibmkahm picture ibmkahm · Feb 22, 2010 · Viewed 19.4k times · Source

in one of my forms a datagridview displays data from a database (of course the number of data (so number of rows) can change). The database connection is in the form load event. I just cant figure out how the height of the whole datagridview is autosized, depending on the number of rows it displays.

Answer

Larry picture Larry · Feb 6, 2013

This is what I managed to find, and it runs fine so far :

int GetDataGridViewHeight(DataGridView dataGridView)
{
    var sum = (dataGridView.ColumnHeadersVisible ? dataGridView.ColumnHeadersHeight : 0) +
              dataGridView.Rows.OfType<DataGridViewRow>().Where(r => r.Visible).Sum(r => r.Height);

    return sum;
}

Thanks to this, I encapsulated my DataGridView in a UserControl so I could implement AutoSize correctly :

// This is in a user control where the datagrid is inside (Top docked)
protected override void OnResize(EventArgs e)
{
    if (AutoSize)
    {
        var height = this.GetDataGridViewHeight(this.dataBoxGridView);
        this.dataBoxGridView.Height = height;
        this.Height = height +this.Padding.Top + this.Padding.Bottom;
    }
}

I did not try (yet) to build a Custom Control directly from the DataGridView to implement this.