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

猜你喜欢

转载自blog.csdn.net/norsd/article/details/81434724