Hide specific cell values in DataGridView

In this post I will show you how to hide a specific cell value in a DataGridView control.

Get a DataGridView and some data for it

Let's suppose we have this pre-populated DataGridView (it really doesn't matter what is the data source):
DataGridView with zero values in cells
Now let's say we want to hide all the "0" values. So actually, if there is no value specified we want to have a blank instead of the default "0" value. This is how we can force the DataGridView to achieve this.

DataGridView with hidden cell values

Just handle the DataGridView.CellPainting event to identify the cell you want to customize.

C# .NET

1 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)

2 {

3     // We are interested in handling the values in the "Value" column only...

4     if (e.ColumnIndex == valueDataGridViewTextBoxColumn.Index)

5     {

6         int cellValue = 0;

7 

8         if (e.Value != null && Int32.TryParse(e.Value.ToString(), out cellValue))

9         {

10             if (cellValue == 0)

11             {

12                 e.CellStyle.ForeColor = e.CellStyle.BackColor;

13                 e.CellStyle.SelectionForeColor = e.CellStyle.SelectionBackColor;

14             }

15         }

16     }

17 }



DataGridView with blank values

Here is the result:

DataGridView with blank values in cells