How to vertically auto size a winforms datagridview control, so that its rows are always visible
.net, c#, datagridview, winforms
Solution
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;
}
Problem
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.