Datagridview's row autoresize

monican picture monican · Nov 23, 2012 · Viewed 10k times · Source

I'm trying to automatically adjust a row's height and I've found it very challenging.

I've already set this property :

DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells.

I've also made it using this other method:

DataGridView.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders)

And also row by row, by using this:

DataGridView.AutoResizeRow(i, DataGridViewAutoSizeRowMode.AllCells)

And also even hardcoded the row's height to a large value, and it didn't work either!! All the rows are shown with their defaults heights.

None of these worked. I'm running out of options.

Most of the rows in the datagridview don't need to be resized. But one of them is filled with values like these:

"a" + "\n" + b + "\n" + "c" + "\n" + "d" + "\n" + "e"

I mean, short values but in different lines. I have to show them in different lines, can't show them all together. But the datagridview shows only the first one and all the other ones are hidden, because the row doesn't autoresize.

Any idea about any other way to do it.

Answer

David Hall picture David Hall · Nov 23, 2012

You need to call the resize method after the data has been changed. From the MSDN article on DataGridView.AutoResizeRows():

The row heights are adjusted only once per method call; if the contents of the rows later change, the rows will not automatically adjust.

This means that you need to call the method after the first and any subsequent loading of the grid. If you are calling this code within the parent form's controller, databinding has not yet happened so the data is not there.

For the first loading using the DataBindingComplete event:

dataGridView1.DataBindingComplete += new
    DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
}

For later updates to cells you will need to find the best place yourself.