New to Telerik UI for WinFormsStart a free 30-day trial

How to Prevent Applying Formatting To Other Columns In RadGridView CellElements

Updated over 6 months ago

Environment

Product VersionProductAuthor
2022.3.913RadGridView for WinFormsMaria Terzieva

Description

A common requirement is to apply style settings to the RadGridView's cell elements. Using the CellFormatting event is a good approach to achieve it. However, the applied style settings might be applied to undesired cell elements after operations like scrolling, grouping, etc.

Undesired formatting

radgridview-applying-formatting

Solution

Due to UI virtualization in RadGridView, the cell elements are created for only visible cells and reused during operations like scrolling, filtering, grouping, etc. In order to prevent applying the formatting to other columns cell elements all customization should be reset for the rest of the cell elements in the CellFormatting event, which is used to access and change the styles of the data cells in the RadGridView. In other words, each "if" statement that applies certain style settings should have the respective "else" clause for resetting these settings. Here is presented a .gif example after resetting all customization of the cell elements:

radgridview-applying-formating-after-reset

C#

public RadForm1()
{
    InitializeComponent();
   
    this.radGridView1.CellFormatting += RadGridView1_CellFormatting;
}

private void RadGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
{
    if(e.CellElement.ColumnInfo.Name == "ProductName")
    {
        e.CellElement.ForeColor = Color.Red;
    }
    else
    {
        e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local);
    }

    if (e.CellElement.ColumnInfo.Name == "Category")
    {
        e.CellElement.DrawImage = true;
        e.CellElement.Image = Properties.Resources.Tori;
        e.CellElement.ImageLayout = ImageLayout.Zoom;
        e.CellElement.TextImageRelation = TextImageRelation.TextAboveImage;
    }
    else
    {
        e.CellElement.ResetValue(LightVisualElement.DrawImageProperty, ValueResetFlags.Local);
        e.CellElement.ResetValue(LightVisualElement.ImageProperty, ValueResetFlags.Local);
        e.CellElement.ResetValue(LightVisualElement.ImageLayoutProperty, ValueResetFlags.Local);
        e.CellElement.ResetValue(LightVisualElement.TextImageRelationProperty, ValueResetFlags.Local);        
    }
}

See Also