I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).
My goal is to display a grid that neatly fills all available width with cells - i.e. no un
Another version of Miroslav Zadravec's code, but slightly more automated and universal:
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = source;
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++) {
dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
dataGridView1.Columns[dataGridView1.Columns.Count].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
void Form1Shown(object sender, EventArgs e)
{
for ( int i = 0; i < dataGridView1.Columns.Count; i++ )
{
int colw = dataGridView1.Columns[i].Width;
dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridView1.Columns[i].Width = colw;
}
}
I put second part into separate event, because I fill datagridvew
in initialization of form and if both parts are there, nothing is changing, because probably autosize calculates widths after datagridview
is displayed, so the widths are still default in Form1()
method. After finishing this method, autosize does its trick and immediately after that (when form is shown) we can set the widths by second part of the code (here in Form1Shown
event). This is working for me like a charm.