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?
Thanks.
To create fill-mode columns for values of varying size and importance. Set the DataGridView. AutoSizeColumnsMode property to Fill to set the sizing mode for all columns that do not override this value. Set the FillWeight properties of the columns to values that are proportional to their average content widths.
Users can make size adjustments by dragging or double-clicking row, column, or header dividers. In column fill mode, column widths change when the control width changes; for example, when the control is docked to its parent form and the user resizes the form.
The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor.
This should work:
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With