1、DataGridView 中添加CellPainting事件方法
2、在CellPainting函数内部进行重绘
代码如下:
private void dgvSteps_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex > -1 && e.RowIndex >= 0)//要进行重绘的单元格
{
Graphics gpcEventArgs = e.Graphics;
Color clrBack = e.CellStyle.BackColor;
Font fntText = e.CellStyle.Font;//获取单元格字体
//先使用北京颜色重画一遍背景
gpcEventArgs.FillRectangle(new SolidBrush(clrBack), e.CellBounds);
//设置字体的颜色
Color oneFore = System.Drawing.Color.Black;
Color secFore = System.Drawing.Color.Red;
string strFirstLine = "黑色内容";
string strSecondLine = "红色内容";
Size sizText = TextRenderer.MeasureText(e.Graphics, strFirstLine, fntText);
int intX = e.CellBounds.Left + e.CellStyle.Padding.Left;
int intY = e.CellBounds.Top + e.CellStyle.Padding.Top;
int intWidth = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
int intHeight = sizText.Height + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);
//第一行
TextRenderer.DrawText(e.Graphics, strFirstLine, fntText, new Rectangle(intX, intY, intWidth, intHeight),
oneFore, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
//另起一行
intY = intY + intHeight - 1;
TextRenderer.DrawText(e.Graphics, strSecondLine, fntText, new Rectangle(intX, intY, intWidth, intHeight),
secFore, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
在同一行后面画
//intX = sizText.Width - 1;//在这行后面添加
//if (intX < e.CellBounds.Width)//能够显示的时候才进行绘制
//{
// intWidth = e.CellBounds.Width - intX;
// TextRenderer.DrawText(e.Graphics, strSecondLine, fntText, new Rectangle(intX, intY, intWidth, intHeight),
// secFore, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
//}
e.Handled = true;
}
}