using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Datagridview_Cell_Color_by_Value
{
//datagridview change cell backcolor based on value
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
DataTable dt = new DataTable();
dt.Columns.Add("Year");
dt.Columns.Add("Jan");
dt.Columns.Add("Feb");
dt.Columns.Add("Mar");
dt.Columns.Add("Apr");
dt.Rows.Add(new object[] { "1978", "35.2", "45.6", "15.2", "13.6" });
dt.Rows.Add(new object[] { "1979", "42.1", "44.3", "21", "10.3" });
dt.Rows.Add(new object[] { "1980", "44.3", "51.2", "22.3", "40.6" });
dt.Rows.Add(new object[] { "1981", "39.6", "39.3", "23.1", "14.9" });
dt.Rows.Add(new object[] { "1982", "48.3", "46.3", "16.3", "11.6" });
dt.Rows.Add(new object[] { "1983", "18.6", "19.4", "18", "35.9" });
dt.Rows.Add(new object[] { "1984", "32.1", "53.6", "17.0", "19.3" });
dt.Rows.Add(new object[] { "1985", "41.2", "56.7", "18.9", "25.8" });
dt.Rows.Add(new object[] { "1986", "38.3", "50.2", "20.1", "22.3" });
dt.Rows.Add(new object[] { "1987", "30.2", "48.3", "28.3", "18.6" });
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 1; i < 5; i++)
{
if (row.Cells[i].Value != null)
{
if (Convert.ToDouble(row.Cells[i].Value) > 40)
{
row.Cells[i].Style.BackColor = Color.LightBlue;
}
else if (Convert.ToDouble(row.Cells[i].Value) > 30)
{
row.Cells[i].Style.BackColor = Color.Yellow;
}
else if (Convert.ToDouble(row.Cells[i].Value) > 20)
{
row.Cells[i].Style.BackColor = Color.Orange;
}
else
{
row.Cells[i].Style.BackColor = Color.OrangeRed;
}
}
}
}
}
}
}