Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 937
ibmkahm Avatar asked Feb 22 '10 09:02

ibmkahm


3 Answers

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.

like image 200
Larry Avatar answered Nov 15 '22 19:11

Larry


If you set DataGridView.AutoSize == true then as you add more rows the grid gets longer. Otherwise you get scrollbars. Unless you've set ScrollBars == Null || Horizontal, in which case the rows just disappear of of the end.

For some reason, DataGridView.AutoSize can only be set programmatically. And there're some odd behaviours observable when you put the grid inside an autosizable control. It doesn't seem to respond to the size of the grid.

I ended up calculating the expected size of the grid from the column, row, header, margin, padding and border sizes, and then sizing the control containing the grid and anchoring the grid on four sides. Felt really clunky but it's the best I could come up with. If you're still around, comment and I'll see if I can find the code, I don't have it on hand.

like image 32
Spike Avatar answered Nov 15 '22 19:11

Spike


MSDN says "This property is not relevant for this class."

MSDN: DataGridView.AutoSize Property

like image 39
Ivan Gerken Avatar answered Nov 15 '22 20:11

Ivan Gerken