RulesManager for WinForms
DataGridView との統合
チュートリアル > 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#
コードのコピー
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#
コードのコピー
class Rules
{
    // HighlightCellsルールを作成します
    public void CreateApplyHighlightCellsRule(C1RulesManager rulesManager)
    {
        // 条件付き書式ルールを適用するセル範囲を定義します
        var itemRange = new CustomItemRange(0, 19, new string[] { "UnitPrice" });
        
        // 条件付き書式ルール式を定義します
        var expressionString = "[CurrentValue] > 20";
        
        // 条件付き書式スタイルを定義します
        var style = new ItemStyle()
        {
            BackColor = Color.FromArgb(255, 199, 206),
            ForeColor = Color.FromArgb(156, 0, 6)
        };

        // HighlightCellsルールを作成します
        var rule = new C1.Win.RulesManager.Rule()
        {                
            Name = "Value greater than 20 on 'UnitPrice'",
            Expression = expressionString,
            Style = style
        };
        
        // セル範囲にルールを適用します
        rule.AppliesTo.Add(itemRange);
        
        // ルールをRulesManagerに追加します
        rulesManager.Rules.Add(rule);
    }
    
    // ColorScalesルールを作成します
    public void CreateApplyColorScalesRule(C1RulesManager rulesManager)
    {
        // 条件付き書式ルールを適用するセル範囲を定義します
        var itemRange = new CustomItemRange(0, 19, new string[] { "UnitsOnOrder" });
        
        // 条件付き書式ルール式を定義します
        var expressionString = "= true";
        
        // 条件付き書式スタイルを定義します
        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)
                    }
                }
            }
        };

        // ColorScalesルールを作成します
        var rule = new C1.Win.RulesManager.Rule()
        {                
            Name = "Color scale on 'UnitsOnOrder'",
            Expression = expressionString,
            Style = style
        };

        // セル範囲にルールを適用します
        rule.AppliesTo.Add(itemRange);

        // ルールをRulesManagerに追加します
        rulesManager.Rules.Add(rule);
    }      
}

Configure FormattableDataGridView

  1. Get the connection string and data source for the FormattableDataGridView control.
    C#
    コードのコピー
    // データソースを取得します
    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;
    }
    
    // 接続文字列を取得します
    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#
    コードのコピー
    // FormattableDataGridViewをスプリッターパネルに追加します
    FormattableDataGridView formattableGrid = new FormattableDataGridView();            
    // FormattableDataGridViewのデータソースを設定します
    formattableGrid.DataSource = GetDataSource();
    // 行ヘッダーを非表示にします
    formattableGrid.RowHeadersVisible = false;
    // DataGridViewの新しい行を非表示にします
    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#
コードのコピー
// RulesMangerルールを適用するコントロールを設定します
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#
コードのコピー
// Rulesクラスを初期化して、ルールを作成および適用します
Rules rules = new Rules();
// メソッドを呼び出します
rules.CreateApplyHighlightCellsRule(c1RulesManager1);           
rules.CreateApplyColorScalesRule(c1RulesManager1);