设置 DevExpress (gridControl中gridView )指定行(row)和单元列(cell)样式(背景颜色,字体),被选中后颜色不被覆盖

首次发布:2022-04-22 11:58

最近更新 2023-11-08

效果图

   

    注册样式事件

this.gridView1.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(this.gridView1_RowCellStyle);
this.gridView1.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(this.gridView1_RowStyle);

    事件方法

//行样式
private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{//原创来自 www.luofenming.com
    //更多可以通过逻辑筛选
    //e.RowHandle  等于当前行时变红
    if (e.RowHandle == this.gridView1.FocusedRowHandle)
    {
        //设置字体样式
        e.Appearance.Font= new System.Drawing.Font("楷体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
        e.Appearance.BackColor = Color.GreenYellow;
    }
}

int standard;
//单元列 样式
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
{
    //更多可以通过逻辑筛选
    //列名为 gridColumn2的单元列
    if (e.Column.Name == "gridColumn2")
    {
        var v = e.CellValue;
        if (v != null)
        {//当单元列名称为  gridColumn2  值大于 standard时,单元列背景颜色变红
            if (int.Parse(v.ToString()) > standard)
            {
                e.Appearance.BackColor = Color.Red;
            }
        }
    }
}

如果需要被选中后颜色不被覆盖,效果如下图

QQ截图20231108133438.png

以下是核心代码

private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
    if (e.RowHandle >= 0)
    {
        string postIs = gridView2.GetRowCellDisplayText(e.RowHandle, gridView2.Columns["TestItem"]);//获取限制变色条件行的值
        if (postIs == "限流特性试验")
        {
            e.Appearance.BackColor = Color.Red;//设置满足条件行背景色为红色
        }
        if(postIs== "效率实验")
        {
            e.Appearance.ForeColor = Color.Green;//设置满足条件行字体色为绿色
        }
    }
}