Reputation: 15
I have a huge problems every time I try to resize my columns and rows. I'm trying to autoresize the columns and the rows with the function:
dataGridView1.AutoResizeColumns();
dataGridView1.AutoResizeRows();
If i put this two lines after I pass the datasource
to dataview
, it doesn't work. I tried to handle the DataSourceBindingComplete
, and idem it doesn't work. I tried to set it in the form.designer.cs
and it doesn't work. then
I tried to make a button
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.AutoResizeColumns();
dataGridView1.AutoResizeRows();
}
and when I click the button everything works perfectly!!! It resizes all my columns and my rows. But i don't want this. I want it automatic. Can you guys help me please and explain why it does that? Doesn't make sense, inside the original code it doesn't work, but in a separate button it works.
Upvotes: 0
Views: 2271
Reputation: 46
I apologize that it took me more than a year to see this post...
Here's what I did to make this "automatic".
private void AutoResizeGrid()
{
if (dataGridView.Columns.Count < 1) return;
dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
dataGridView.AutoResizeRows(DataGridViewAutoSizeRowsMode.DisplayedCells);
}
private void MatrixDataGridView_ClientSizeChanged(object sender, EventArgs e)
{
if (!this.Visible) return;
AutoResizeGrid();
}
private void MatrixDataGridView_Scroll(object sender, ScrollEventArgs e)
{
if (!this.Visible) return;
AutoResizeGrid();
}
Before adding this code, I went to the Designer and I set "AutoSizeColumnsMode" and "AutoSizeRowsMode" both to "DisplayedCells". This causes automation when the grid first receives the data. The code above causes automation when a resize or scroll event happens.
Upvotes: 0
Reputation: 51
Have you tried setting the DataGridViewAutoSizeColumnsMode
before you set the source, if possible?
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.DataSource = SourceList; // Your Collection here
dataGridView1.AutoResizeRows();
}
Upvotes: 1
Reputation: 750
This has worked for me.
Set AutoSizeColumnsMode and AutoSizeRowsMode values to AllCells from None in the designer.
Upvotes: 1