在我的一种形式中,datagridview 显示来自数据库的数据(当然数据的数量(所以行数)可以改变)。数据库连接在表单加载事件中。我只是无法弄清楚整个datagridview的高度是如何自动调整的,具体取决于它显示的行数。
4 回答
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.
如果您设置 DataGridView.AutoSize == true ,那么当您添加更多行时,网格会变得更长。否则你会得到滚动条。除非你设置了 ScrollBars == Null || 水平的,在这种情况下,行只是从末尾消失。
出于某种原因,DataGridView.AutoSize 只能以编程方式设置。当您将网格放在可自动调整大小的控件中时,可以观察到一些奇怪的行为。它似乎对网格的大小没有反应。
我最终根据列、行、标题、边距、填充和边框大小计算了网格的预期大小,然后调整包含网格的控件的大小并将网格锚定在四个边上。感觉真的很笨重,但这是我能想到的最好的。如果您还在,请发表评论,我会看看能否找到代码,我手头没有。
MSDN 说“此属性与此类无关。”
我就是这样做的。要设置 DataGridView 的高度,您可以使用它的 Set Height 属性。在表单加载时,您可以使用此代码隐藏 datagridview。dataGridViewName.Height = 0;
然后在从数据库中获取行时。我们可以使用以下方法根据行数获取datagridview高度。
private int dataGridViewHeight()
{
int sum = this.dataGridViewName.ColumnHeadersHeight;
foreach (DataGridViewRow row in this.dataGridViewName.Rows)
sum += row.Height + 1; // I dont think the height property includes the cell border size, so + 1
return sum;
}