Click here to Skip to main content
15,881,709 members
Articles / Programming Languages / C#
Tip/Trick

Row Header Cell Images in DataGridView

Rate me:
Please Sign up or sign in to vote.
4.55/5 (10 votes)
24 May 2011CPOL 53.6K   1.9K   23   5
This post helps to load image in row header cell of a datagridview.

Introduction

This post helps to load image in row header cell of a datagridview. As per my investigation, it is found that we cannot directly load an image into a row header cell (this can be false though). But I figured out a way to load an image in row header cell by converting the image into an icon – then show it using the event dataGridView1_RowPostPaint (and I’m not sure whether this is the best way).

RowHeaderCellImages/Image_1.png

I have added the ’RedCross’ image in an imageList in my project. If we try to resize the image to a larger extent, the quality of image will be deformed. Try to load images in the image list with the exact size; we prefer to show it in the row header cell.

C#
private void dataGridView1_RowPostPaint
	(object sender, DataGridViewRowPostPaintEventArgs e)
{
    //Convert the image to icon, in order to load it in the row header column
    Bitmap myBitmap = new Bitmap(imageList1.Images[0]);
    Icon myIcon = Icon.FromHandle(myBitmap.GetHicon());

    Graphics graphics = e.Graphics;

    //Set Image dimension - User's choice
    int iconHeight = 14;
    int iconWidth = 14;

    //Set x/y position - As the center of the RowHeaderCell
    int xPosition = e.RowBounds.X + (dataGridView1.RowHeadersWidth / 2);
    int yPosition = e.RowBounds.Y + 
	((dataGridView1.Rows[e.RowIndex].Height - iconHeight) / 2);

    Rectangle rectangle = new Rectangle(xPosition, yPosition, iconWidth, iconHeight);
    graphics.DrawIcon(myIcon, rectangle);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer UVJ Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGreat Code !! tnx I conveted in .net Pin
Vecchia Volpe8-Dec-15 6:54
Vecchia Volpe8-Dec-15 6:54 
Generalgood Pin
omerelili21-May-12 19:28
omerelili21-May-12 19:28 
thx
GeneralMy vote of 4 Pin
MBigglesworth7925-May-11 0:53
MBigglesworth7925-May-11 0:53 
GeneralGood One Pin
vsareesh25-May-11 0:33
vsareesh25-May-11 0:33 
Generalnice Pin
baihualin198324-May-11 15:25
baihualin198324-May-11 15:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.