Tuesday, May 22, 2012

Having Text and Image in One Single Column of DataGridView


DataGridView's Cell_Painting event could be utilized to achieve the above. You need a DataGridView and ImageList in which an Image to be attached. The following simple code in event will be able to achieve this:

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
 {

    if (e.RowIndex >= 0 && e.ColumnIndex == 0 && Convert.ToInt32(e.Value.ToString()) > 0)
    {
        e.PaintBackground(e.ClipBounds, false);
       dataGridView1[e.ColumnIndex, e.RowIndex].ToolTipText = e.Value.ToString();
       PointF p = e.CellBounds.Location;
       p.X += imageList1.ImageSize.Width;

      e.Graphics.DrawImage(imageList1.Images[0], e.CellBounds.X, e.CellBounds.Y, 16, 16);
       e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, p);
       e.Handled = true;
    }

}
 
Refer DataGridView FAQ in the following Thread:
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/b5ab78d6-a760-4f29-ac89-46bad51ba30a







9 comments:

Vinay Yadav said...

Simply Awesome bro. you are the savior.

Vinay Yadav said...

Thank you bro. you are the savior. Just Awesome Code.

RambleCampbell said...

Very nice -- about 100x simpler than most solutions out there. One minor problem: it removes the row highlight on the cell in question when FullRowSelect is set to true. Apparently the highlight isn't being painted due to the handling. But, still, very helpful.

Dale said...

A simple solution to the highligh problem is to simply add the following before the DrawImage line

if (dataGridViewTests.Rows[e.RowIndex].Selected)
e.PaintBackground(e.ClipBounds,true);

Hasan said...

That was pretty useful thanks a lot for sharing :)

Sinan said...

Thanks Appreciated.

Nishantha said...

It works perfectly. You save my time, thanks a lot

Dipak Rathod said...

It Works Perfactly.You save my time, thanks a lot

Dipak Rathod said...

It works perfectly. You save my time, thanks a lot....