New to Telerik UI for WinForms? Download free 30-day trial

How to customize specific cell while another cell value is changing

Environment

Product Version Product Author
2021.1.223 RadGridView for WinForms Nadya Karaivanova

Description

This article will demonstrate how you can customize a specific cell depending on the changing value in another cell. For example if there is a calculated column in the grid, the calculated cell always change its value when one of the depending on it cells changes its value. You may want to indicate the user somehow that the value in the calculated cell is about to be changed. This example shows how you can color a cell when another cell in being edited in a way to indicate that its value would change, and after edit, reset the color to its default one.

customize-cell-based-on-another-cell.gif

Solution

To achieve this, we can use the Style property that GridViewCellInfo offers. The GridViewCellInfo.Style property gives direct access to the cell’s visual properties and allows to customize it. We should subsribe to the CellEditorInitialized event and set the desired cell style. Then, reset it in the CellEndEvent event.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
        GridViewDecimalColumn col = new GridViewDecimalColumn();
        col.Name = "Calculated Column";
        col.HeaderText = "Order value";
        radGridView1.Columns.Add(col);
        radGridView1.Columns["Calculated Column"].Expression = "UnitsInStock * UnitPrice";
        this.radGridView1.CellEditorInitialized += this.RadGridView1_CellEditorInitialized;
        this.radGridView1.CellEndEdit += this.RadGridView1_CellEndEdit;
    }
    GridViewCellInfo cell;
    private void RadGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e)
    {
        GridSpinEditor editor = radGridView1.ActiveEditor as GridSpinEditor;
        if (editor != null && e.Column.Name == "UnitsInStock" || e.Column.Name == "UnitPrice")
            cell = radGridView1.Rows[e.RowIndex].Cells[3];
        StyleCell(cell);
    }
    private void StyleCell(GridViewCellInfo cell)
    {
        cell.Style.CustomizeFill = true;
        cell.Style.GradientStyle = GradientStyles.Solid;
        cell.Style.BackColor = Color.Red;
    }
    private void RadGridView1_CellEndEdit(object sender, GridViewCellEventArgs e)
    {
        cell.Style.CustomizeFill = false;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        this.productsTableAdapter.Fill(this.nwindDataSet1.Products);

    }
}

In this article