颜色代码datagridview [英] colour code datagridview

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

问题描述

使用c#winform 4.0

datagridview有几列,包括ItemID
列 datagridview已填充了几行.
有些行具有相同的ItemID值.
我希望对具有相同ItemID的行进行颜色编码.

例如:
第2行和第5行可能具有相同的ItemID.这两行应该只有一种颜色
第6和7行可能具有相同的ItemID.这两行应具有一种颜色.即不同于第2行和第5行
...

using c# winform 4.0

The datagridview has several columns including column ItemID
The datagridview has been populated with several rows.
Some of the rows have the same ItemID value.
I would like the rows with the same ItemID to be colour coded.

For example:
rows 2 and 5 may have the same ItemID. These two rows should have one colour
rows 6 and 7 may have the same ItemID. These two rows should have a one colour. i.e. different to the rows 2 and 5
...

How is this done please?

推荐答案

DataGridView CellFormatting 事件可用于此目的,如下所示:
The CellFormatting event of DataGridView can be used for this purpose as shown below:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    DataGridView DataGridView1 = new DataGridView();
    Button ButtonUpdate = new Button();
    BindingSource BindingSource1 = new BindingSource();
    DataTable DataTable1 = new DataTable();
    Color[] colorTable;
    private void Form1_Load(object sender, EventArgs e)
    {
        colorTable = new Color[]{
               Color.Blue, Color.Red, Color.Green,
               Color.Pink, Color.Plum, Color.Cyan};
        DataTable1.Columns.Add("ItemId", typeof(int), null);
        {
            DataTable1.Rows.Add(1);
            DataTable1.Rows.Add(2);
            DataTable1.Rows.Add(2);
            DataTable1.Rows.Add(5);
            DataTable1.Rows.Add(5);
            DataTable1.Rows.Add(6);
            DataTable1.Rows.Add(6);
            DataTable1.Rows.Add(7);
            DataTable1.Rows.Add(7);
        }
        BindingSource1.DataSource = DataTable1;
        DataGridView1.DataSource = BindingSource1;

        DataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(DataGridView1);
        DataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(DataGridView1_CellFormatting);

    }

    void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 0)
        {
            try
            {
                int val = (int)DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                e.CellStyle.BackColor = colorTable[val % 6];
            }
            catch
            {
                return;
            }
        }
    }
}


这篇关于颜色代码datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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