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

How to Add User-Defined Values in RadDropDownList

Updated over 6 months ago

Environment

Product VersionProductAuthor
2019.2.618RadDropDownList for WinFormsDesislava Yordanova

Description

RadDropDownList is an enhanced alternative to the standard Windows Forms combo box control. It can be either bound to data sources or populated with items programmatically. However, in both cases, RadDropDownList is designed to allow users to enter valid values according to the filled RadDropDownList.Items collection. If the user enters any text that don't match any record in the Items collection, this value won't be accepted as valid and it won't be preserved as SelectedValue after you navigate to another control.

user-defined-values-in-dropdownlist001

Solution

In order to keep the user-defined values, add a record with the custom text to the applied DataSource collection. Consider that the RadDropDownList control is bound to a DataTable:

C#

public RadForm1()
{
    InitializeComponent();

    this.radDropDownList1.DisplayMember = "Name";
    this.radDropDownList1.ValueMember = "Id";
    this.radDropDownList1.DataSource = GetEmployees();
    this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest;
    this.radDropDownList1.DropDownStyle = RadDropDownStyle.DropDown;
    this.radDropDownList1.DropDownListElement.TextBox.TextBoxItem.TextBoxControl.PreviewKeyDown += TextBoxControl_PreviewKeyDown;
}

private object GetEmployees()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Id", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Rows.Add(1, "Mark Brown");
    dt.Rows.Add(2, "Anna Smith");
    dt.Rows.Add(3, "John Adams");
    return dt;
}

private void TextBoxControl_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyData == Keys.Enter)
    {
        bool found = false;
        string text = this.radDropDownList1.DropDownListElement.TextBox.TextBoxItem.TextBoxControl.Text;

        // Checking if the typed value exists in the datasource of the column.
        DataTable dt = this.radDropDownList1.DataSource as DataTable;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["Name"].ToString() == text)
            {
                found = true;
                break;
            }
        }
        if (!found)
        {
            DataRow newEmployeesRow = dt.NewRow();
            newEmployeesRow["Name"] = text;
            newEmployeesRow["Id"] = dt.Rows.Count+1;
            dt.Rows.Add(newEmployeesRow);

            this.radDropDownList1.SelectedValue = newEmployeesRow["Id"];
        }
    }
}
    

Now, when you enter any custom text and press Enter to confirm that value, a new record will be added to the DataSource collection and the selected item will be preserved when RadDropDownList looses focus.

user-defined-values-in-dropdownlist002

See Also