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

How to Filter a GridViewCommandColumn

Environment

Product Version Product Author
2022.1.222 RadGridView for WinForms Desislava Yordanova

Description

GridViewCommandColumn is not purposed to provide filtering as its data cells are expected to offer a button element, not a text value. This tutorial will demonstrate a sample approach how to provide such a filtering functionality.

gridview-filter-command-column001

Solution

A possible solution is to use a GridViewTextBoxColumn and construct a custom cell element for its data cells that contain a button. Thus, the filtering functionality will be allowed out of the box considering the text value of each cell.

You can find below a sample code snippet for your reference. Let's consider that the RadGridView control is bound to the Northwind.Products table:


public Form1()
{
    InitializeComponent();          

    CustomGridViewTextBoxColumn customColumn = new CustomGridViewTextBoxColumn();
    customColumn.HeaderText = "Custom Column";
    customColumn.FieldName = "ProductName";
    this.radGridView1.Columns.Add(customColumn);
    this.radGridView1.EnableFiltering = true;
}

public class CustomGridViewTextBoxColumn : GridViewTextBoxColumn
{
    public override Type GetCellType(GridViewRowInfo row)
    {
        if (row is GridViewDataRowInfo)
        {
            return typeof(ButtonGridDataCellElement);
        }
        return base.GetCellType(row);
    }
}

public class ButtonGridDataCellElement : GridDataCellElement
{
    public override void AddEditor(IInputEditor editor)
    {
        if (this.GridControl.CurrentRow is GridViewDataRowInfo)
        {
            return;
        }
        base.AddEditor(editor);
    }

    public ButtonGridDataCellElement(GridViewColumn column, GridRowElement row) : base(column, row)
    {
    }
    protected override Type ThemeEffectiveType
    {
        get
        {
            return typeof(GridDataCellElement);
        }
    }
    public override bool IsCompatible(GridViewColumn data, object context)
    {
        return data is CustomGridViewTextBoxColumn && context is GridDataRowElement;
    }

    RadButtonElement btn = new RadButtonElement();
    protected override void CreateChildElements()
    {
        base.CreateChildElements();
        this.Children.Add(btn);
        btn.Click += Btn_Click;
    }

    private void Btn_Click(object? sender, EventArgs e)
    {
        RadMessageBox.Show(this.Value + "");
    }


    protected override void SetContentCore(object value)
    {
        base.SetContentCore(value);
        this.DrawText = false;
        this.btn.Text = this.Text;
    }

    public RadButtonElement Button { get { return this.btn; } }
}