Use this extension in your code, it sets the datagridview
, and leaves the columns "free" if the user wants to resize, and already formats the columns that are decimal.
public static class Extensions
{
public static void AjeitaDataGridView(this DataGridView dataGridView)
{
//para deixar o tamanho "certo e editavel" o tamanho da coluna
// all cells bloqueia o usuario a nao editar
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
int colw = dataGridView.Columns[i].Width;
if (dataGridView.Columns[i].ValueType == typeof(Decimal))
{
dataGridView.Columns[i].DefaultCellStyle.Format = "N2";
}
//
dataGridView.Columns[i].Width = colw;
}
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}
and in your code just call..
this.datagridview1.AjeitaDataGridView();
Reference: How do you Automatically resize Columns in a Datagridview control AND allow the user to resize the Columns on that same grid?
Marco, just a question, why do you take the column size, and then again arrow the column size? this makes it rendered?
– Nicola Bogar
I know it sounds stupid. I found an example of this in an answer in SO-en.. If I find it later, I put the reference here.. but this makes when you
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
the column does not return to the value of "before", you can make a test.. commenting on the linedataGridView.Columns[i].Width = colw;
, you’ll see it won’t work...– Marco Giovanni
I put the reference in the answer...
– Marco Giovanni