C# 为 datagridview 的行中的相同值着色 [英] C# coloring the same values in row of datagridview

查看:24
本文介绍了C# 为 datagridview 的行中的相同值着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个填充了行的 datagridview.现在为了使某些数据更加清晰,我想为某些单元格的背景着色.但是有一些警告,我想要着色的列数量可能会有所不同.为了让事情更清楚,我将草拟一个假数据网格:

Say I have a datagridview filled with rows. Now to make certain data more distinct I'd like to color the background of certain cells. There's some caveats though, the amount of columns I want coloring in can vary. To make things more clear I'll sketch up a fake datagrid:

Name Thing2 col1 col2 col3
tes   test   1    1     2
t2t   ers    3    3     3
der   zoef   2    3     1

现在,col1-col3 单元格需要根据它们的值进行着色.第一列中的单元格将始终为绿色(按照惯例),偏离它的单元格将显示为红色.因此,第一行的 col1 和 col2 为绿色,col3 为红色等等.关于如何最好地解决这个问题的任何想法?

Now, the col1-col3 cells need to be colored, depending on their value. The cells in the first column will always be green (by convention) cells deviating from it will be colored red. So, the first row will have col1 and col2 colored green and col3 red et cetera. Any ideas to how i'd best approach this problem?

推荐答案

我建议使用 CellFormating 事件.

I suggest using CellFormating event.

首先使用 e.RowIndex 获取与当前行关联的对象,然后根据当前列 (e.ColumnIndex) 和对象的属性为当前单元格着色.

First get object associated with current row using e.RowIndex and then color current cell according to current column (e.ColumnIndex) and your object's properties.

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= customerBindingSource.Count)
                return;

            switch (e.ColumnIndex)
            {
                case 3:
                    Customer customer = (Customer)customerBindingSource[e.RowIndex];
                    if (customer.Salary > 1000)
                        e.CellStyle.BackColor = Color.Red;
                    break;
            }
        }

这篇关于C# 为 datagridview 的行中的相同值着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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