适合的dataGridView大小行的和列的总大小大小、适合、dataGridView

2023-09-03 02:45:09 作者:陌路離殤

我想打一个DataGridView的大小,使其适合列和行总大小。关于总高度,我设法它适合栏的高度这样的:

I want to make a dataGridView's size to fit the columns and rows total size. About total height, I managed to fit it to columns's height like that:

const int datagridLines = 30;
s.Height = dataGridView2.Columns[0].HeaderCell.Size.Height;
for (byte i = 0; i < datagridLines; i++)
{
  dataGridView2.Rows.Add();
  s.Height += dataGridView2.Rows[i].Height;
}
dataGridView2.ClientSize = s;

我尝试了一些东西,也契合了宽度,但没有运气。有什么建议?

I tried some things to also fit the width but no luck. Any suggestions?

感谢。

推荐答案

这应该工作:

int height = 0;
foreach (DataGridViewRow row in dataGridView1.Rows) {
    height += row.Height;
}
height += dataGridView1.ColumnHeadersHeight;

int width = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns) {
    width += col.Width;
}
width += dataGridView1.RowHeadersWidth;

dataGridView1.ClientSize = new Size(width + 2, height + 2);

本+ 2的宽度高度的值是一个忽悠的因素要占在DataGridView的宽度内饰元素。我记得看到code的地方,可以让你得到这个值,而硬codeD的数字,但我找不到它了。

The + 2 to the width and height values are a fudge factor to account for the width of the DataGridView's interior elements. I recall seeing code somewhere that will allow you to get this value without the hard coded numbers but I can't find it now.