image column in datagrid for windows forms

I know the question was asked a while back but here's what I found from another forum. The code assumes that the images are stored in an ImageList.:

http://www.vbdotnetforums.com/showthread.php?t=2124

using System;
using System.Windows.Forms;
using System.Drawing;

namespace ImageColumnStyleTest
{
/// <summary>
/// Summary description for ImageColumnStyle.
/// </summary>
public class ImageColumnStyle : DataGridColumnStyle
{
private Image image = null;
public static ImageList imageList = null;

public ImageColumnStyle() : base()
{
}

protected override void Abort(int rowNum)
{
Invalidate();
}

protected override void Edit(CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
}

protected override bool Commit(CurrencyManager dataSource, int rowNum)
{
return true;
}

protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum)
{
Paint(g, bounds, source, rowNum, false);
}

protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight)
{
Paint(
g,
bounds,
source,
rowNum,
Brushes.Red,
Brushes.Blue,
alignToRight);
}

protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
{
int index = (int)base.GetColumnValueAtRow(source, rowNum);
InitImage(index);

Rectangle rect = new Rectangle(bounds.Location, imageList.ImageSize);
g.FillRectangle(backBrush, bounds);
g.DrawImage(image, rect);
}

protected override int GetPreferredHeight(Graphics g, object value)
{
return imageList.ImageSize.Height;
}

protected override int GetMinimumHeight()
{
return imageList.ImageSize.Height;
}

protected override Size GetPreferredSize(Graphics g, object value)
{
return imageList.ImageSize;
}

private void InitImage(int index)
{
if(imageList != null && imageList.Images.Count >= index + 1)
{
image = imageList.Images[index];
}
}
}
}
 
Last edited:
Back
Top