根据条件更改 datagridview 单元格颜色 [英] Changing datagridview cell color based on condition

查看:32
本文介绍了根据条件更改 datagridview 单元格颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将数据从数据库加载到 datagridview 并有两列目标值和体积,其中体积 > 目标值,体积单元格应为绿色,体积 <目标值则音量应为红色.我试过了,但我做不到.

I have loaded the data from database to datagridview and have two columns target value and volume where volume >target value that volume cell should be in green color and volume < target value then volume should be in red color. I tried it but I am not able to do it.

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    if (dataGridView1.Rows.Count > 0 && dataGridView1.Columns.Count > 0)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if (Volume > target value)
            {
                cell.Style.BackColor = Color.AliceBlue;
            } 

推荐答案

你需要这样做

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow Myrow in dataGridView1.Rows) 
    {            //Here 2 cell is target value and 1 cell is Volume
        if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition 
        {
            Myrow .DefaultCellStyle.BackColor = Color.Red; 
        }
        else
        {
            Myrow .DefaultCellStyle.BackColor = Color.Green; 
        }
    }
}

同时也看看 Cell Formatting

这篇关于根据条件更改 datagridview 单元格颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆