Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

c# - DataGridView Auto Height - How to AutoSize DataGridView Height?

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

dataGridView_SearchResults.AutoSize = true;

However this makes the Horizontal scroll bar disappear, the the DataGridView gets cut off.

How can I autosize the height without losing the horizontal scroll bar?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...