Walkthrough / Integrate Rules Manager with DataGridView
Integrate Rules Manager with DataGridView

This topic will guide you through the steps to apply conditional formatting on DataGridView by integrating the RulesManager control with the DataGridView control.

Applying conditional formatting on DataGridView using the RulesManager control

Set up the application

  1. Create a new Windows Forms App.
  2. Add C1SplitContainer control to the Form and dock it in the Form. Add a panel to the C1SplitContainer control and dock C1SplitterPanel1 to the left.
  3. Add the C1RulesManager control to C1SplitterPanel2 and set its Dock property to fill.
  4. From the Properties window, set the Name property of the C1RulesManager control to rulesManager.

Implement IFormattableView interface

As RulesManager provides conditional formatting for a control which supports IFormattableView interface, DataGridView must implement the IFormattableView Interface to integrate with the RulesManager control.

C#
Copy Code
public class FormattableDataGridView : DataGridView, IFormattableView
{
    public event ListChangedEventHandler DataChanged;
    public event EventHandler<ItemFormattingEventArgs> ItemFormatting;

    IEnumerable<string> IFormattableView.GetFieldNames()
    {
        var fields = new List<string>();
        foreach (var column in Columns)
        {
            var name = (column as DataGridViewColumn)?.DataPropertyName;
            if (!string.IsNullOrEmpty(name))
            {
                fields.Add(name);
            }
        }

        return fields;
    }

    int IFormattableView.GetItemCount()
    {
        return Rows.Count;
    }

    object IFormattableView.GetValue(int row, string col)
    {
        return this[col, row].Value;
    }

    protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
    {
        base.OnDataBindingComplete(e);
        DataChanged?.Invoke(this, new ListChangedEventArgs(ListChangedType.Reset, 0));
    }

    protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
    {
        var columnIndex = e.ColumnIndex;
        var rowIndex = e.RowIndex;
        if (columnIndex >= 0 && rowIndex >= 0)
        {
            var ifea = new ItemFormattingEventArgs(rowIndex, Columns[columnIndex].DataPropertyName);
            ItemFormatting?.Invoke(this, ifea);

            var ruleStyle = ifea?.Style;
            if (ruleStyle != null)
            {
                var cellStyle = e.CellStyle;

                var backColor = ruleStyle.BackColor;
                if (!backColor.IsEmpty)
                {
                    cellStyle.BackColor = backColor;
                }

                var foreColor = ruleStyle.ForeColor;
                if (!foreColor.IsEmpty)
                {
                    cellStyle.ForeColor = foreColor;
                }

                var fontStyle = ruleStyle.FontStyle;
                if (cellStyle.Font.Style != fontStyle && fontStyle != FontStyle.Regular)
                {
                    cellStyle.Font = new Font(cellStyle.Font, fontStyle);
                }
            }
        }

        base.OnCellPainting(e);
    }

    void IFormattableView.UpdateView()
    {
        Invalidate();
    }
}

Create conditional formatting rules

Create a class named Rules to create the CreateApplyHighlightCellsRule and CreateApplyColorScalesRule methods which can be used to define conditional formatting rules, such as highlight cells and color scale, respectively. These rules can be defined in RulesManager, using the Name, Expression and Style properties of the Rule class.

C#
Copy Code
class Rules
{
    //Create HighlightCells Rule
    public void CreateApplyHighlightCellsRule(C1RulesManager rulesManager)
    {
        //Define cell range to apply conditional formatting rule
        var itemRange = new CustomItemRange(0, 19, new string[] { "UnitPrice" });
        
        //Define conditional formatting rule expression
        var expressionString = "[CurrentValue] > 20";
        
        //Define conditional formatting style: Solid
        var style = new ItemStyle()
        {
            BackColor = Color.FromArgb(255, 199, 206),
            ForeColor = Color.FromArgb(156, 0, 6)
        };

        //Create HighlightCells Rule
        var rule = new C1.Win.RulesManager.Rule()
        {                
            Name = "Value greater than 20 on 'UnitPrice'",
            Expression = expressionString,
            Style = style
        };
        
        //Apply rule to cell range
        rule.AppliesTo.Add(itemRange);
        
        //Add rule to RulesManager
        rulesManager.Rules.Add(rule);
    }
    
    //Create ColorScales Rule
    public void CreateApplyColorScalesRule(C1RulesManager rulesManager)
    {
        //Define cell range to apply conditional formatting rule
        var itemRange = new CustomItemRange(0, 19, new string[] { "UnitsOnOrder" });
        
        //Define conditional formatting rule expression
        var expressionString = "= true";
        
        //Define conditional formatting style: Gradient
        var style = new ItemStyle()
        {
            Gradient = new GradientSettings()
            {
                BackgroundPoints = new GradientPoint[]
                {
                    new GradientPoint(GradientPointType.MinValue)
                    {
                        Color = Color.FromArgb(248, 105, 107)
                    },
                    new GradientPoint(GradientPointType.Percent)
                    {
                        Color = Color.FromArgb(255, 235, 132),
                        Value = 50.0f
                    },
                    new GradientPoint(GradientPointType.MaxValue)
                    {
                        Color = Color.FromArgb(99, 190, 123)
                    }
                }
            }
        };

        //Create ColorScales Rule
        var rule = new C1.Win.RulesManager.Rule()
        {                
            Name = "Color scale on 'UnitsOnOrder'",
            Expression = expressionString,
            Style = style
        };

        //Apply rule to cell range
        rule.AppliesTo.Add(itemRange);

        //Add rule to RulesManager
        rulesManager.Rules.Add(rule);
    }      
}

Configure FormattableDataGridView

  1. Get the connection string and data source for the FormattableDataGridView control.
    C#
    Copy Code
    //Get Datasource
    private DataTable GetDataSource()
    {
        var comm = "Select TOP 20 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel from Products;";
        //var comm = "Select TOP 20 * from Products;";
        var conn = GetConnectionString();
        var da = new OleDbDataAdapter(comm, conn);
        var dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    
    //Get Connection String
    static string GetConnectionString()
    {
        var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\ComponentOne Samples\Common";
        var conn = @"provider=microsoft.jet.oledb.4.0;data source={0}\c1nwind.mdb;";
        return string.Format(conn, path);
    }
    
  2. Initialize and configure the FormattableDataGridView control and add it to C1SplitterPanel1.
    C#
    Copy Code
    //Configure and add FormattableDataGridView to splitter panel
    FormattableDataGridView formattableGrid = new FormattableDataGridView();            
    //Set FormattableDataGridView datasource
    formattableGrid.DataSource = GetDataSource();
    //Hide row headers
    formattableGrid.RowHeadersVisible = false;
    //Hide DataGridView new row
    formattableGrid.AllowUserToAddRows = false;
    formattableGrid.Dock = DockStyle.Fill;
    c1SplitContainer1.Panels[0].Controls.Add(formattableGrid);
    

Integrate RulesManager with DataGridView

To integrate RulesManager with FormattableDataGridView, use SetC1RulesManager method of the RulesManager class as shown in the following code:

C#
Copy Code
//Set the control on which to apply RulesManger rules
c1RulesManager1.SetC1RulesManager(formattableGrid, c1RulesManager1);

Apply Rules

Define an instance of the Rules class and invoke the CreateApplyHighlightCellsRule and CreateApplyColorScalesRule methods to add rules to RulesManager, which will be applied to the FormattableDataGridView.

C#
Copy Code
//Initialize Rules class to create and apply rules
Rules rules = new Rules();
//Invoke methods to create and apply rules
rules.CreateApplyHighlightCellsRule(c1RulesManager1);           
rules.CreateApplyColorScalesRule(c1RulesManager1);