I have a DataGridView
that displays a limited number of rows, never more than 5. This DataGridView
is placed on a DataRepeater
control so it's usually displayed many times on the screen. What I want to achieve is that all grids are resized to the size of their contents so they don't display scroll bars if 4 or 5 items are in them or take up extra vertical space if only 1 or 2 items are there.
The grids only contain text data. They are data bound controls, so they'll need to resize if the underlying data source changes (I guess the DataBindingComplete
event would be suitable).
How may I achieve this? Is counting rows the best option? Thanks in advance.
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.
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.
The DataGrid control is limited to displaying data from an external data source. The DataGridView control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together.
Max value, i.e. 2,147,483,647. The DataGridView's RowCount cannot hold a number more than this because it's an integer.
Since your control is data-bound, I would set the Height
property on the DataGridView to the sum of the heights of its rows (plus some margin) in the DataBindingComplete
event:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
var height = 40;
foreach (DataGridViewRow dr in dataGridView1.Rows) {
height += dr.Height;
}
dataGridView1.Height = height;
}
I took hmqcnoesy's answer and expanded on it and created a function to also include the width. And to use on any grid.
Note: Set AutoSizeCells = AllCells on the grid.
public static DataGridView SetGridHeightWidth(DataGridView grd, int maxHeight, int maxWidth)
{
var height = 40;
foreach (DataGridViewRow row in grd.Rows)
{
if(row.Visible)
height += row.Height;
}
if (height > maxHeight)
height = maxHeight;
grd.Height = height;
var width = 60;
foreach (DataGridViewColumn col in grd.Columns)
{
if (col.Visible)
width += col.Width;
}
if (width > maxWidth)
width = maxWidth;
grd.Width = width;
return grd;
}
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