Displaying a status image in a datagridview

  • Thread starter Thread starter Simon Harvey
  • Start date Start date
S

Simon Harvey

Hi all,

Can someone show me, or direct me to some code which deals with the
following (pretty standard) requirement:

I have a database column with an integer indicating status e.g 1 =
Available, 2 = Out of Stock and so forth.

In the datagrid, I would like to be able to display an appropriate
coloured icon according to the integer value.

The images are available in a resource file.

Can anyone suggest how I do this? Or at the very least tell me what
event I should use from the datagridview and whether I should be using a
databound column or not?

HUGE thanks to anyone who can advise

Kindest Regards

Simon
 
Here is one way to do it. Just go ahead and have this column in your
DataGridView as a bound column. Then handle the CellPainting event and
draw the bitmap yourself instead of letting the grid to the default
drawing. Here is code that does this assuming the images have been
loaded into a ImageList.

//put some bitmaps into an ImageList
images = new ImageList();
images.Images.Add(SystemIcons.Error.ToBitmap());
images.Images.Add(SystemIcons.WinLogo.ToBitmap());
images.Images.Add(SystemIcons.Question.ToBitmap());



//this.images is an ImageList with your bitmaps
void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex > -1 && e.Value != null)
{
e.PaintBackground(e.ClipBounds, false);
int index = (int) e.Value; // the 1, 2 or 3
Point pt = e.CellBounds.Location;// where you want the bitmap
in the cell
pt.X += 5;
pt.Y += 1;
this.images.Draw(e.Graphics, pt, index);
e.Handled = true;
}
}

================
Clay Burch
Syncfusion, Inc.
 
A DataGridView has an interesting feature. If you databind a column to a
byte array, it assumes that the byte array is an image from a database and
draws the image if it can.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Back
Top