Auto height of DataGridView - how to adjust data size of DataGridView?

I am trying to make the height of my DataGridView AutoSize based on the number of rows it contains. Currently, I have been able to accomplish this with the following line:

dataGridView_SearchResults.AutoSize = true;

However, this causes the horizontal scrollbar to fade; the DataGridView is disabled.

How can I authorize the height without losing the horizontal scrollbar?

+1
source share
1 answer

Option 1 - Override GetPreferredSize

GetPreferredSize DataGridView new Size(this.Width, proposedSize.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));
    }
}

2 -

DataGridView, , GetPreferredSize new Size(0, 0), DataGridView , , DataGridView. RowsAdded, RowsRemoved, , :

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;
}

, , Font, , Paint.

3 - MaximumSize

, , DataGridView, MaximumSize . new Size(this.dataGridView1.Width, 0):

dataGridView1.MaximumSize = new Size(this.dataGridView1.Width, 0);
dataGridView1.AutoSize = true;

MaximumSize , , 1 2.

+2

All Articles