in one of my forms a datagridview displays data from a database (of course the number of data (so number of rows) can change). The database connection is in the form load event. I just cant figure out how the height of the whole datagridview is autosized, depending on the number of rows it displays.
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.
If you set DataGridView.AutoSize == true then as you add more rows the grid gets longer. Otherwise you get scrollbars. Unless you've set ScrollBars == Null || Horizontal, in which case the rows just disappear of of the end.
For some reason, DataGridView.AutoSize can only be set programmatically. And there're some odd behaviours observable when you put the grid inside an autosizable control. It doesn't seem to respond to the size of the grid.
I ended up calculating the expected size of the grid from the column, row, header, margin, padding and border sizes, and then sizing the control containing the grid and anchoring the grid on four sides. Felt really clunky but it's the best I could come up with. If you're still around, comment and I'll see if I can find the code, I don't have it on hand.
MSDN says "This property is not relevant for this class."
This is how i did. to set height of DataGridView you can use its Set Height property.On form load you can use this code to hide datagridview. dataGridViewName.Height = 0;
Then While fetching Rows from Database. we can use below method to get datagridview Height according to number of Rows.
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;
}
© 2022 - 2024 — McMap. All rights reserved.