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

Custom Values in GridViewComboBoxColumn

Environment

Product Version 2018.1 220
Product RadGridView for WinForms

Description

By default one cannot add values that are not contained in the popup when GridViewComboBoxColumn is used. This article demonstrates how you can add any value and still be able to chose from predefined options.

Solution

Firs you need to add a custom editor, this way you can override the Value property and return the text when no value is selected.

Use Custom editor

class CustomDropDownListEditor : RadDropDownListEditor
{
    public override object Value
    {
        get
        {
            object result = base.Value;
            if (result == null || string.IsNullOrEmpty(result.ToString()))
            {
                var editor = this.EditorElement as RadDropDownListElement;
                return editor.Text;
            }
            return result;
        }
        set
        {
            base.Value = value;
            var editor = this.EditorElement as RadDropDownListElement;
            if (editor.SelectedValue == null)
            {
                editor.TextBox.TextBoxItem.Text = value.ToString();
            }
        }
    }
    public override void BeginEdit()
    {
        base.BeginEdit();
        var editor = this.EditorElement as RadDropDownListElement;
        editor.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown;
    }
}

Once the editor is ready you can change it by using the EditorRequired event.

Change Default Editor

private void RadGridView1_EditorRequired(object sender, EditorRequiredEventArgs e)
{
    if (e.EditorType == typeof(RadDropDownListEditor))
    {
        e.EditorType = typeof(CustomDropDownListEditor);
    }
}

The final step is to create a custom column. This is necessary because the text is formated by looking in the DataSource of the column.

Create Custom Column

class CustomGridViewComboBoxColumn : GridViewComboBoxColumn
{
    public override object GetLookupValue(object cellValue)
    {
        object result = base.GetLookupValue(cellValue);
        if (result == null)
        {
            return cellValue;
        }
        return result;
    }
}

That is all now you will be able to add any value in the GridViewComBoxColumn. A complete Visual Studio solution is available here.

In this article