public Form1() { InitializeComponent(); LoadData();
}
private void LoadData() { DataTable tblDatas = new DataTable(); tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
tblDatas.Columns.Add("Name", Type.GetType("System.String")); tblDatas.Columns.Add("Version", Type.GetType("System.String")); tblDatas.Columns.Add("Age", Type.GetType("System.String")); tblDatas.Rows.Add(new object[] { 1, "a", "b", "12" }); tblDatas.Rows.Add(new object[] { 2, "a", "b", "15" }); tblDatas.Rows.Add(new object[] { 3, "a", "b", "30" }); tblDatas.Rows.Add(new object[] { 4, "a", "b", "25" }); tblDatas.Rows.Add(new object[] { 5, "a", "b", "30" });
dataGridView1.DataSource = tblDatas; }
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex > -1) { int intGrade = Convert.ToInt32(this.dataGridView1.Rows[e.RowIndex].Cells["dgvAge"].Value); if (intGrade ==30) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; } else if(intGrade==25) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Brown; } } }
效果图如下: