Share via


Datagridview header center align: Why does my code keep getting changed?

Question

Tuesday, July 26, 2011 5:49 PM

Hi all,

I'm doing this to center the header and data in column 3 and 4 of my datagridview control:

// 
// Column4
// 
this.Column4.DefaultCellStyle = dataGridViewCellStyle2;
this.Column4.HeaderText = "Qty (S2)";
this.Column4.Name = "Column4";
this.Column4.ReadOnly = true;
this.Column4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.Column4.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column4.HeaderCell.Style.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;

everytime I change a property (of any control) the block above gets changed to this:

// 
// Column4
// 
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Column4.DefaultCellStyle = dataGridViewCellStyle2;
this.Column4.HeaderText = "Qty (S2)";
this.Column4.Name = "Column4";
this.Column4.ReadOnly = true;
this.Column4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;

The same things happens to column 3. I finally place the two lines below "InitializeComponent();". It looks like it is ok but why does my code kept getting modified?

 

Thanks.

All replies (2)

Tuesday, July 26, 2011 5:56 PM âś…Answered

To add: 

to allign 1st column you do:

dataGridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //cells alignment
dataGridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; ///header alignment

...

but after InitializeComponent() method, otherwise you wlill get an error, becuase control has not been yet initialized!

Mitja


Tuesday, July 26, 2011 5:50 PM

Put the code bellow "InitializeComponent()" method.

Because this method creates all the controls in DGV!

After that, you do your own modifications.

Mitja