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

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

问题描述

说我有一个datagridview充满了行。
现在让某些数据更加清晰我想为某些单元格的背景着色。
虽然有一些注意事项,我想要着色的列数量可以有所不同。
为了使事情更清楚我会绘制一个假的datagrid:

 名称Thing2 col1 col2 col3 
tes test 1 1 2
t2ters 3 3 3
der zoef 2 3 1

现在,col1-col3单元格需要着色,具体取决于它们的值。第一列中的单元将总是绿色的(根据惯例)偏离它的单元将被着色成红色。
所以,第一行将col1和col2着绿色和col3红色等。
任何想法如何最好地解决这个问题?

解决方案

我建议使用CellFormating事件。 >

使用 e.RowIndex 首先获取与当前行关联的对象,然后根据当前列为当前单元格着色(<$ c $

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

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


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

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?

解决方案

I suggest using CellFormating event.

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天全站免登陆