Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force resize of DataGridView columns

Tags:

c#

winforms

I've got a simple form with a DataGridView element on it. In the constructor the grid columns get added and the DataTable gets set. When I then call AutoResizeColumns() it doesn't resize the columns as it would when called by e.g. a button event. The code looks like this (simplified):

public MyDialog()
{
   InitializeComponent();
   dgv.Columns.AddRange(SomeClass.MyColumns);
   dgv.DataSource = SomeClass.Table;
   // This doesn't work:
   dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}

AutoResizeColumns() works in general but not at that point. Btw, I need this to implement a behavior like it is requested/described here. Any ideas?

like image 289
AndOne Avatar asked Dec 07 '10 15:12

AndOne


2 Answers

I had the same issue until I set the autosize mode:

dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
like image 180
Andrew Mortimer Avatar answered Oct 10 '22 05:10

Andrew Mortimer


Additionally, I believe the object needs to be VISIBLE before the resize is done... for some reason, the painting doesn't appear to happen as one would expect.

like image 26
DRapp Avatar answered Oct 10 '22 06:10

DRapp