Category / Section
How to set background color to a row based on the data associated to the row?
1 min read
Background color of a row can be set based on data associated with the row by customizing the GridCellTextViewRenderer and by overriding OnLayout() method. In the OnLayout() method, you can get the associated row data from the DataColumn property in the view based on which the background color can be customized.
MainActivity.cs
In MainActivity, remove the existing TextViewRenderer from SfDataGrid.CellRenderers dictionary and add the customized renderer(CustomTextViewRenderer).
public class MainActivity : Activity { private SfDataGrid sfGrid; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); sfGrid = new SfDataGrid (BaseContext); sfGrid.CellRenderers.Remove("TextView"); sfGrid.CellRenderers.Add("TextView", new CustomTextViewRenderer ()); sfGrid.ItemsSource = (new OrderInfoRepository ().OrderInfoCollection); SetContentView(sfGrid); } }
CustomTextViewRenderer.cs
public class CustomTextViewRenderer: GridCellTextViewRenderer { public CustomGridCell() { } protected override void OnLayout(RowColumnIndex rowColumnIndex, View view, int left, int top, int right, int bottom) { base.OnLayout(rowColumnIndex, view, left, top, right, bottom); var rowData = (view as GridCell).DataColumn.RowData as OrderInfo; if (rowData.OrderID > 100 && rowData.CustomerID == "Tim Adams") (view.Parent as View).SetBackgroundColor(Color.BlanchedAlmond); } }
Screenshot:
Sample Link: How to set background color to a row based on row data?