Introduction

Normally, a DataGridView control won't allow you to set a background image for its column headers. This code will do that, in a very easy way.

I made this just to simplify what has already been done by the original author.

I supplied an image, which is a stripe (1 pixel wide), to use a background. You don't need more, because it will be stretched to fill the whole columnheader.Now, since it is a semi-transparent PNG, you'll see the color of the Columheader. By doing so, you won't need to supply a different image for each colour you'd like to paint your Headers - you just change the ColumnHeadersDefaultCellStyle.BackColor property and you're done.

It couldn't be any easier, I think.

Background

As the original article, this code illustrates how to custom draw a DataGridView Column Headers.

My version is just an optimized version of the original, with much less code and a small improvement (the mentioned small-sized transparent image that lets the underlying color be seen through).

There is very little code: an enumeration (a set of grouped constants), a method and its call inside an event of the DataGridView. Nothing more than this!!

Oh, well, I forgot to mention that a little bit of initialization code is required (here I do that directly in the Form's Load event handler, but you can put it into a method and call that method from the Load event).

The way it aligns text is how you would draw the text on any other control: check how user wants the text to be aligned and operate accordingly with the StringFormat object you'll use in combination with the DrawString method.

There's two properties to do this: Alignment (horizontally) and LineAlignment (vertically); and three values Near (Left or Up), Far (Right or Down), and Center (Middle).

The combination of these properties with their values gives the nine possible alignments for a text.

The way it draws the image can be tricky, so...

... you'll notice a section, in the above code, delimited by two "all asterisks" comment lines.

That's room for improvements (surely due to my misinterpretation of the DrawImage method).

I hope that other programmers will find this code useful as per their needs.

Comments and Discussions

I noticed there's loads of stuff in the code sample, but to add the main form with the representation of the grid view itself only involved importing the form and the png images associated with it.
I hope later I can update it with more special effects
Thanks for your great contribution though.