DataGridView 自绘Row的背景

19 篇文章 0 订阅

DataGridView 可以指定row的BackColor, 这个在许多文章中都有, 但是如何自绘Row的背景,这个却不多见。
例如一行背景颜色需要能左侧,中间,右侧的背景各不相同。
实现如下:
1. 要求默认的Cell的背景颜色为Transparent, 否则绘画是无效的

base.CellFormatting += base_CellFormatting;
base.RowPrePaint += base_RowPrePaint;

 private void base_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
 {
     var row = base.Rows[e.RowIndex];
     row.DefaultCellStyle.BackColor = Color.Transparent;
 }

2.在绘画Row的函数中绘画背景

        private void base_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {            
               int x = e.RowBounds.Left;
               int y = e.RowBounds.Top;
               int width = base.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed);
               int height = e.RowBounds.Height;


               using(SolidBrush bru = new SolidBrush(Color.Blue)
               {
                   e.Graphics.FillRectangle(bru, x, y, width, height);
               }                 
        }

3.在实际使用中,我们往往会用到下面几个工具函数:

DataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed) //获取DataGridView整个显示的长度
DataGridView.Columns[$"{nameof(DataClass.Item)}"]  //DataClass为绑定的数据类型
DataGridView.GetCellDisplayRectangle(columnIndex, rowIndex, false) //获取某一个Cell(或者Column)的位置
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值