DataGridView.Columns
, change AutoSizeMode
to a valid one, collect width value and set it back after change AutoSizeMode
to DataGridViewAutoSizeColumnMode.None
). Form.Show()
or Form.ShowDialog()
. So I put this code snippet in the Form.Shown
event and this works for me. My transformed code, reguardless of whatever DataGridView.AutoSizeColumnsMode
set before, I use DataGridViewColumn.GetPreferredWidth()
instead of changing DataGridViewColumn.AutoSizeMode
and set the width value immediately, then change DataGridView.AutoSizeColumnsMode
once:
private void form_Shown(object sender, EventArgs e)
{
foreach (DataGridViewColumn c in dataGridView.Columns)
c.Width = c.GetPreferredWidth(DataGridViewAutoSizeColumnMode.DisplayedCells, true);
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
Be sure to set
dataGridView.AllowUserToResizeColumns = true;
I don't know how come this only works after the form is shown.