Help coloring individual cells in datagridview based on cells beside them.
Hi, I have this requirement to color individual cells in the datagridview
based on the value of the cells right of them. There is how the data looks like:
ID Time D1 D1Q D2 D2Q D3 D3Q .....
1 '1/1/2007 00:05' 35 BLUE 23.5 GREEN 42 RED
2 '1/1/2007 00:10' 38 BLUE 24.8 YELLOW 38 YELLOW
3 '1/1/2007 00:15' 41 RED 23.1 YELLOW 33 RED
4 '1/1/2007 00:20' 36 RED 24.5 GREEN 39 YELLOW
5 '1/1/2007 00:25' 38 BLUE 25.2 GREEN 45 YELLOW
On the Datagridview, the ID, DxQs are hidden. But the DxQ dictates what
the Dx's cells colors.
In the above's sample data, the column D1, will show 35 with blue cell background,
38 with blue cell bg, 41 red, 36 red and 38 having blue cell background. Same goes
for the rest of the columns.
About the data, the number of columns can vary depends on the user selection.
So, it can be 1 item + the color column, to n number of columns.
Can someone give advise where should this be done and what is the most efficient way
because almost always, there are lots of data being shown on the datagridview.
Thanks in advance.
Rick..
Hi,akaRickShaw
Have a look at my sample, and put attention to the code in bold.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class DgvBkColor : Form
{
public DgvBkColor()
{
InitializeComponent();
}
private void DgvBkColor_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Columns.Add("Time",typeof(DateTime));
dt.Columns.Add("D1", typeof(int));
dt.Columns.Add("D1Q",typeof(Color));
dt.Rows.Add(1, DateTime.Now, 35, Color.Red);
dt.Rows.Add(2, DateTime.Now, 36, Color.Red);
dt.Rows.Add(3, DateTime.Now, 56, Color.Beige);
dt.Rows.Add(4, DateTime.Now, 34, Color.Blue);
dt.Rows.Add(5, DateTime.Now, 67, Color.Red);
dt.Rows.Add(6, DateTime.Now, 89, Color.Yellow);
this.dataGridView1.DataSource = dt;
this.dataGridView1.Columns["D1Q"].Visible = false;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex != this.dataGridView1.NewRowIndex)
{
if (e.ColumnIndex == this.dataGridView1.Columns["D1"].Index)
{
e.CellStyle.BackColor = (Color)this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value;
}
}
}
}
}
Hope it helps
Best Regards.
Zhixin