Note: The question is about Windows Forms .NET DataGrid
which is deprecated and no longer available in .NET CORE and .NET 5.
It's strongly recommended to upgrade your solution to use DataGridView;
Anyways, if you are stuck with DataGrid and cannot easily update to DataGridView, the answer is for you.
Customizing appearance of DataGrid
To customize a DataGrid control, you usually need to define a DataGridTableStyle and add a few DataGridColumnStyle to it.
To have full control on appearance of the rows and columns, you usually need to create custom column styles by driving from one of the existing built-in column styles like DataGridTextBoxColumn or DataGridBoolColumn or the base DataGridColumnStyle. Then you can customize the behavior by overriding properties and methods of the class.
You will find this article very useful:
Example - Change row background color based on cell value of a specific column
Here I create a new column style by deriving from the built-in DataGridTextBoxColumn and overriding its Paint method. In the method, I check if the value of the first column is odd number:
public class MyDataGridTextBoxColumn : DataGridTextBoxColumn
{
protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source,
int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
{
var idCellValue = ((DataRowView)source.List[rowNum])["Id"];
var brush = backBrush;
if (idCellValue != DBNull.Value && ((int)idCellValue) % 2 == 1)
brush = Brushes.Yellow;
base.Paint(g, bounds, source, rowNum, brush, foreBrush, alignToRight);
}
}
Then to use it:
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
dt.Rows.Add(3, "C");
var dg = new DataGrid();
dg.Dock = DockStyle.Fill;
var ts = new DataGridTableStyle();
ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn()
{ MappingName = "Id", HeaderText = "Id" });
ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn()
{ MappingName = "Name", HeaderText = "Name" });
dg.TableStyles.Add(ts);
this.Controls.Add(dg);
dg.DataSource = dt;
}
And you will see the result:
Note: It definitely makes more sense to not put any business logic inside the custom Column, instead you can raise a Formatting event, and put any logic inside the event handler and pass formatting data back to the column, using event arguments.