DataGridView 中单元格显示不一样颜色方法

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;
            }
        }


  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值