What better way to align columns of Datagridview C#

Asked

Viewed 783 times

0

What is the best way to align the columns of a Datagridview, because if placed to align by the column name size is cut the cells that are larger than the column name size, and when placed to align by the cell and the cell size is smaller than the header, the header is cut, I’m starting to mess with part of Windows Forms now and I’m wondering, what is the best way to present the Grid records? inserir a descrição da imagem aqui

2 answers

1


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?

  • 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 line dataGridView.Columns[i].Width = colw;, you’ll see it won’t work...

  • I put the reference in the answer...

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.