- This topic helps you learn how to change DataGridView rows color in C# programming.
- You can easily change the DataGrid row color with the help of DataGridViewCellStyle.
DataGridView – Change Datagridview rows color in C#
- The DataGridView control provides a customizable table for displaying data.
- DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms.
- DataGridView class allows us to customization of cells, rows, columns, and borders through the use of its properties
- Each cell within the DataGridView control can have its own style, such as text format, background color, foreground color, font etc.
- All cells derive from the DataGridViewCell base class.
DataGridViewCellStyle Class – Change Datagridview rows color in C#
- DataGridViewCellStyle Class represents the formatting and style information applied to individual cells within a DataGridView control.
Change Datagridview rows color in C# – Working
- First creates an object for the DataGridViewCellStyle which controls the DataGridView rows foreground and background color.
|
1 2 3 4 5 6 7 |
DataGridViewCellStyle grid_style = default(DataGridViewCellStyle); int Sel_Row = -1; private void Form1_Load(object sender, EventArgs e) { grid_style = new DataGridViewCellStyle(); grid_style.BackColor = Color.LightCoral; } |
- In the SelectionChanged event handler,It reset the previously selected row’s DefaultCellStyle property to Nothing.
- Then set newly selected row’s DefaultCellStyle property to the style that created at frame load.
|
1 2 3 4 5 6 7 8 9 |
private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (Sel_Row >= 0) { DataGridView1.Rows[Sel_Row].DefaultCellStyle = null; } Sel_Row = DataGridView1.CurrentRow.Index; DataGridView1.CurrentRow.DefaultCellStyle = grid_style; } |
Change Datagridview rows color in C# – Complete Code
|
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 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { DataGridViewCellStyle grid_style = default(DataGridViewCellStyle); int Sel_Row = -1; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { grid_style = new DataGridViewCellStyle(); grid_style.BackColor = Color.LightCoral; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (Sel_Row >= 0) { DataGridView1.Rows[Sel_Row].DefaultCellStyle = null; } Sel_Row = DataGridView1.CurrentRow.Index; DataGridView1.CurrentRow.DefaultCellStyle = grid_style; } } } |
Change Datagridview rows color in C#






