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;
}
}
}
}