• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 604
  • Last Modified:

VB.Net - DataGridView Center Column Headings

Good Day Experts!

I am having trouble centering the column headings in my DataGridView.  When I have the columns defined prior to loading the DataGrid with data it works fine.  But I can't do that this time.  So, I am trying to do everything programatically. I have the data centered in the columns but I cannot get the column headings centered. Here is what I am trying:

Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
dgrdPossDupBills.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle

Does anything look wrong with my coding?

Thanks,
jimbo99999
0
Jimbo99999
Asked:
Jimbo99999
  • 5
  • 4
1 Solution
 
Éric MoreauSenior .Net ConsultantCommented:
try this one:

dataGridView1.Columns(0).HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter
0
 
Jimbo99999Author Commented:
Thanks for replying.  However, it did not work. The column headings are still left justified.

Thanks,
jimbo99999
0
 
CodeCruiserCommented:
Where did you put this code? After binding the grid?
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Jimbo99999Author Commented:
I have tried it before and after setting the datasource of the DataGrid to the DataTable.  
Everything else works...the readonly, the autosizing and centering of the data in the columns.
0
 
CodeCruiserCommented:
Try following

Dim row As Windows.Forms.DataGridViewRow = dgrdPossDupBills.Rows(-1)
' Loop through header cells
For Each HeaderCell As Windows.Forms.DataGridViewHeaderCell In row.Cells
HeaderCell.Style.Alignment = Windows.Forms.DataGridViewContentAlignment.MiddleCenter
Next
0
 
Jimbo99999Author Commented:
Thanks for responding

I am receiveing and error indicating the Index was out of range.  Must be non-negative and less than the size of the collection.

jimbo99999
0
 
CodeCruiserCommented:
Try changing -1 to 0.
0
 
Jimbo99999Author Commented:
Received error: Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.DataGridViewHeaderCell'
0
 
CodeCruiserCommented:
Ok. Here is the result of my test


SCR
0
 
Jimbo99999Author Commented:
Excellent, that did the trick for me.

I will certainly add your assistance on the topic to my reference.

Thanks,
jimbo99999
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now