效果图:
1:创建列
dataGridView.Columns.Add("autoSetting", "自動設定");
2:创建行
dataGridView.Rows.Add(1);
dataGridView.Rows[0].Cells[0].Value = Image.FromFile("question-fill.png"); // 设置图片路径
dataGridView.Rows[0].Cells[0].ValueType = typeof(Image); // 设置单元格的值类型为Image
dataGridView.Rows[0].Cells[0].ToolTipText = "手動設定";
3:dataGridView绑定CellPainting事件,重新画单元格和图片及字体
private void DataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dataGridView = sender as DataGridView;
if (e.ColumnIndex == 0 && e.Value is Image)
{
// 获取图片和文字
Image image = (Image)e.Value;
Font defaultFont = dataGridView1.Font;
string text = "手動設定";
Size imageSize = image.Size;
Rectangle textRect = new Rectangle(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height);
// 设置文字格式(如颜色,字体等)
using (Brush textBrush = new SolidBrush(e.CellStyle.ForeColor))
{
// 填充背景色以防止选择
e.Graphics.FillRectangle(new SolidBrush(e.CellStyle.BackColor), textRect);
// 绘制文字
e.Graphics.DrawString(text, defaultFont, textBrush, textRect, StringFormat.GenericDefault);
}
// 绘制图片
float textWidth = MeasureTextWidth(text, dataGridView.Font);
e.Graphics.DrawImage(image, e.CellBounds.Left + textWidth, e.CellBounds.Top + 2);
// 绘制单元格边框
using (Pen pen = new Pen(dataGridView.GridColor))
{
// 计算下方线的位置
int bottomLineY = e.CellBounds.Top + e.CellBounds.Height - 1;
// 绘制下方线
e.Graphics.DrawLine(pen, e.CellBounds.Left, bottomLineY, e.CellBounds.Right, bottomLineY);
// 计算右方线的位置
int rightLineX = e.CellBounds.Left + e.CellBounds.Width - 1;
// 绘制右方线
e.Graphics.DrawLine(pen, rightLineX, e.CellBounds.Top, rightLineX, bottomLineY);
}
// 防止进一步的绘制
e.Handled = true;
}
}
4:项目引入图片修改属性