How to vertically automate the size of a datagridview winforms control so that its rows are always visible

I have DataGridViewone that displays a limited number of lines, but no more than 5. This one DataGridViewis placed in the control DataRepeater, so it usually appears many times on the screen. I want all meshes to be resized to the size of their contents, so they do not display scrollbars if they contain 4 or 5 elements or occupy additional vertical space if there are only 1 or 2 elements.

Lattices contain only text data. These are data-bound controls, so they will need to resize if the original data source changes (I think the event DataBindingCompletewould be appropriate).

How can i achieve this? Is row counting the best option? Thanks in advance.

+5
source share
3 answers

Since your control is data bound, I would set the property Heightin the DataGridView to the sum of the heights of my rows (plus some value) in the event DataBindingComplete:

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    var height = 40;
    foreach (DataGridViewRow dr in dataGridView1.Rows) {
        height += dr.Height;
    }

    dataGridView1.Height = height;
}
+13
source

This value can be any. You should check in your grid to find out what is the best value to set the height.

var height = 40;

Edited by:

To find the real height value, you need to add the grid location and the height of the header . Something like that.

int height = dgv.Location.Y + dgv.ColumnHeadersHeight;
foreach (DataGridViewRow dr in dgv.Rows) {
   height += dr.Height; // Row height.
}
dgv.Height = height;
0
source

I accepted the hmqcnoesy answer and expanded it and created a function that should also include width. And use on any grid.

Note. Set AutoSizeCells = AllCells in the grid.

    public static DataGridView SetGridHeightWidth(DataGridView grd, int maxHeight, int maxWidth)
    {
        var height = 40;
        foreach (DataGridViewRow row in grd.Rows)
        {
            if(row.Visible)
                height += row.Height;
        }

        if (height > maxHeight)
            height = maxHeight;

        grd.Height = height;

        var width = 60;
        foreach (DataGridViewColumn col in grd.Columns)
        {
            if (col.Visible)
                width += col.Width;
        }

        if (width > maxWidth)
            width = maxWidth;

        grd.Width = width;

        return grd;
    }
0
source

All Articles