Ali Tor
Ali Tor

Reputation: 2945

Why doesn't cell text alignment doesn't work in DataGridView in C#?

I want to make an input box and I have a DataGridView. But it does't work to align the text content of headers or cells.

My code to create DataGridView at runtime:

DataGridView CreateInputBox(int proc,int mac)
        {
            DataGridView databox = new DataGridView();
            for (int i = 0; i < mac; i++)
            {
                databox.Columns.Add("col" + i, "M" + i);
                databox.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            for (int i = 0; i < proc; i++)
            {
                databox.Rows.Add();
            }
            databox.AutoSize = true;
            databox.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            return databox;
        }

The result:

enter image description here

So how can I do the alignment for the header and cells?

Upvotes: 0

Views: 990

Answers (2)

Littledaem
Littledaem

Reputation: 51

The code above is only to center the cells foreach column but not the header of each column.

Try to add this line in your "for" :

databox.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

Src: Changing DataGridView Header Cells' Text Alignment And The Font Size

Upvotes: -1

Ivan Yurchenko
Ivan Yurchenko

Reputation: 3871

If I understood correctly, the answer is here: Right align a column in datagridview doesn't work

And the problem is in the Sorting as when it’s enabled the DataGrid reserves some place for a sort glyph. So if you disable the sorting it should work as you expect:

this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;

Adding this as an answer so everybody who will get here in the future will easily find the way to resolve the problem.

Upvotes: 2

Related Questions