'Hatching DataGridView Cell
I have WinForms project in C# that it has DataGridView control.
I'm looking for something to express that the DataGridView cell will not be valued.
In excel app hatching is a good way for that purpose. So I want to hatch DataGridView cell similar excel cell as you see in picture below.
I guess I should use CellPainting event. But I couldn't achieve that. If anyone has done something similar to this? Thanx.
Solution 1:[1]
You can handle CellPainting event and then fill the cell using a HatchBrush. You also need to invalidate the control in the event of scroll and enable double buffering to prevent flicker.
Here is an example:
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("C1");
dt.Columns.Add("C2");
dt.Columns.Add("C3");
dt.Rows.Add("X", "X", "O");
dt.Rows.Add("X", DBNull.Value, DBNull.Value);
dt.Rows.Add(DBNull.Value, DBNull.Value, DBNull.Value);
dataGridView1.DataSource = dt;
dataGridView1.CellPainting += DataGridView1_CellPainting;
dataGridView1.Scroll += (_, __) => dataGridView1.Invalidate();
dataGridView1.GetType().GetProperty("DoubleBuffered",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance).SetValue(dataGridView1, true);
}
private void DataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if(e.Value==DBNull.Value)
{
using(var b= new HatchBrush(HatchStyle.ForwardDiagonal,
Color.Black, Color.White))
{
e.Graphics.FillRectangle(b, e.CellBounds);
e.Paint(e.ClipBounds, DataGridViewPaintParts.All &
~DataGridViewPaintParts.Background);
e.Handled = true;
}
}
}
Above example is using ForwardDiagonal as HatchStyle.
In above example, I've filled the background of the cells which have DBNull.Value as their value. You can use any other condition, for example based on having the cell as ReadOnly.
Here is the screenshot of the result:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


