views:

1097

answers:

2

I have a DataGridView which I add data to programatically. I have the AutoSizeRowsMode set to AllCells and the WrapMode on RowsDefaultCellStyle set to True. If I add a multiline row to the DataGridView it shows up fine (autoscaling the row to show the multiple lines). However, if I hide the column that has the multiline data (so that the columns left only have single line data) the row resizes to single row but when I reshow the hidden column the rows aren't resized. If I resize the form then the rows will correct.

The following code shows how I am toggling the visibility of the column: notificationDataGridView.Columns[1].Visible = !notificationDataGridView.Columns[1].Visible;

Can anyone help me out with how to fix this? I've tried every combination of Invalidate and Refresh I can think of.

+1  A: 

Ok, I don't know if this is a bug in the DataGridView or whatever, but here's a hack to make it work. After the call to:

notificationDataGridView.Columns[1].Visible = !notificationDataGridView.Columns[1].Visible;

add these two lines of code:

notificationDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.NotSet;
notificationDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

Don't ask me why, but this seems to work. If anyone has a better solution, please post it!

BFree
I lost carriage returns in multiline cells with this method. The answer from @Russ worked for me.
Aidan Ryan
+1  A: 

I came across a similar problem with row heights not resizing correctly. In my DataGridView I am using the CellFormatting event to write custom data to a DataGridViewTextBoxColumn, which has AutoSizeRowsMode=AllCells and DefaultCellStyle.WrapMode=DataGridViewTriState.True on the relevant column. I use \r\n in the cell text for that column to add extra lines. Upon changing the data to add an extra line to one of the rows, it didn't resize so didn't show the extra line I added. I tried the above workaround to try to force it to redraw the row heights, but it didn't work. The following nasty workaround did work for me though:

dataGridView.Width++;
dataGridView.Width--;

Strangely this hack only worked by resetting the Width, not the Height.