Backcolor of a Single Cell in DataBoundGrid

28 Apr 20211 minute to read

This page explains How to Change the BackColor of a Single Cell and more details.

How to Change the BackColor of a Single Cell

In GridDataBoundGrid, you cannot set cell specific properties like BackColor (other than CellValue or text) using an indexer. The reason is that in GridDataBoundGrid, the only data storage is the bound datasource, which only holds a single value per cell. It does not hold TextColor, BackColor, or any of the other many cell specific properties that are found in GridStyleInfo object.

This code does not work.

//Sets the backcolor of cell(8,10).
this.gridDataBoundGrid1[8, 10].BackColor = Color.Red;
'Sets the backcolor of cell(8,10).
Me.gridDataBoundGrid1(8, 10).BackColor = Color.Red;

So, in order to set cell specific properties in GridDataBoundGrid, you must catch PrepareViewStyleInfo event (or Model.QueryCellInfo event). In your handler, check e.RowIndex and e.ColIndex, and if these point to the cell you want to change, set e.Style to the value you want.

private void gridDataBoundGrid1_PrepareViewStyleInfo(object sender, GridPrepareViewStyleInfoEventArgs e)
    if(e.ColIndex == 2 && e.RowIndex == 2) 
         e.Style.BackColor = Color.Red;
Private Sub gridDataBoundGrid1_PrepareViewStyleInfo(ByVal sender As Object, ByVal e As GridPrepareViewStyleInfoEventArgs)
If e.ColIndex = 2 And e.RowIndex = 2 Then
e.Style.BackColor = Color.Red
End If
End Sub