Reputation: 171
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?
Upvotes: 7
Views: 11425
Reputation: 2370
I had the same issue until I set the autosize mode:
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
Upvotes: 16
Reputation: 48139
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.
Upvotes: 10
Reputation: 8786
You need to use AutoResizeColumns()
after your DataGridView
has data in it. That is the reason. Make sure SomeClass.Table
get the data before you call AutoResizeColumns()
Upvotes: 2