DataGridView 自绘Row的背景

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)的位置

posted on   norsd  阅读(4)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示