How to change datagridview row back color with source code and fore color with source code in c# dynamically.
Cell formating event dynamically change backcolor in datagridview and cell color in datagridview in c# source code.
Write the source code in datagridview cellformating event to change back color and font color row color in datagridview in source code, If you want to change datagridview row color dynamically with source code.
Output:
Soruce Code:
Person.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FormExample11 { class Person { string name; string lastname; int age; public Person(string name, string lastname, int age) { this.name = name; this.lastname = lastname; this.age = age; } public string Name { get => name; set => name = value; } public string Lastname { get => lastname; set => lastname = value; } public int Age { get => age; set => age = value; } } } |
Form.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
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 FormExample11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<Person> pList; private void Form1_Load(object sender, EventArgs e) { pList = new List<Person>(); pList.Add(new Person("Henry","Johan",40)); pList.Add(new Person("Jacob","Wilson",25)); pList.Add(new Person("Jack", "Lopez", 25)); pList.Add(new Person("Levi", "Lee", 40)); pList.Add(new Person("Mateo", "Davis", 23)); pList.Add(new Person("Martin","Lunge",38)); dataGridView1.DataSource = pList; } private void btnFilter_Click(object sender, EventArgs e) { DataGridViewCellStyle style1 = new DataGridViewCellStyle(); style1.BackColor = Color.Red; style1.ForeColor = Color.White; DataGridViewCellStyle style2 = new DataGridViewCellStyle(); style2.BackColor = Color.White; style2.ForeColor = Color.Red; int min = Convert.ToInt32(txtMin.Text); int max = Convert.ToInt32(txtMax.Text); foreach (DataGridViewRow row in dataGridView1.Rows) { int ageRow = Convert.ToInt32(row.Cells[2].Value); if (ageRow >= min && ageRow <= max) row.DefaultCellStyle = style1; else row.DefaultCellStyle = style2; } } } } |