你需要处理
CellPainting
事件
DataGridView
此示例显示如何在绑定列中绘制图像
数据表格控件
Image zero, negative, positive;
Load
事件和来自文件、资源或存储图像并分配给这些变量的任何位置的图像。设置数据绑定。为要在其中绘制图标的单元格设置适当的左填充:
private void Form1_Load(object sender, EventArgs e)
{
var list = new[] {
new { C1 = "A", C2 = -2 },
new { C1 = "B", C2 = -1 },
new { C1 = "C", C2 = 0 },
new { C1 = "D", C2 = 1 },
new { C1 = "E", C2 = 2 },
}.ToList();
dataGridView1.DataSource = list;
zero = new Bitmap(16, 16);
using (var g = Graphics.FromImage(zero))
g.Clear(Color.Silver);
negative = new Bitmap(16, 16);
using (var g = Graphics.FromImage(negative))
g.Clear(Color.Red);
positive = new Bitmap(16, 16);
using (var g = Graphics.FromImage(positive))
g.Clear(Color.Green);
//Set padding to have enough room to draw image
dataGridView1.Columns[1].DefaultCellStyle.Padding = new Padding(18, 0, 0, 0);
}
细胞绘画
数据表格控件
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//We don't need custom paint for row header or column header
if (e.RowIndex < 0 || e.ColumnIndex != 1) return;
//We don't need custom paint for null value
if (e.Value == null || e.Value == DBNull.Value) return;
//Choose image based on value
Image img = zero;
if ((int)e.Value < 0) img = negative;
else if ((int)e.Value > 0) img = positive;
//Paint cell
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
e.Graphics.DrawImage(img, e.CellBounds.Left + 1, e.CellBounds.Top + 1,
16, e.CellBounds.Height - 3);
//Prevent default paint
e.Handled = true;
}
手柄
FormClosing
事件来处理图像:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Dispose images
if (zero != null) zero.Dispose();
if (negative != null) negative.Dispose();
if (positive != null) positive.Dispose();
}