Skip to main content Skip to footer

How to clear selected value in C1ComboBox

When a ComboBox is configured to restrict user input strictly to values present in its ItemsDataSource, attempting to manually erase the text or clear the selection often throws an argument out of range exception. This happens because the control interprets an empty text box as an invalid entry that does not exist in its items collection, preventing users from resetting a filter or clearing their choice.

Solution
The most user-friendly way to allow a blank or null selection when enforcing strict list matching is to add a Custom Button directly into the ComboBox interface. This button can be dedicated to resetting the control's value back to an empty state.

To implement this, you add a custom action button to the control's buttons collection. When this button is clicked, you programmatically set the SelectedIndex to -1 and clear the text. To ensure the validation logic accepts this empty state without throwing an exception, you must also handle the PreValidating event. Inside this event, check if the text is empty; if it is, explicitly set e.Succeeded = true. This bypasses the strict item collection lookup for blank values, seamlessly resetting your data filter or clearing the selection.

 private void Form1_Load(object sender, EventArgs e)
 {
     //setting datasource
     c1ComboBox1.ItemsDataSource = GetItems();

     //handling pre validating event to cancel the validation according to our own logic
     c1ComboBox1.PreValidation.Validation = PreValidationType.PreValidatingEvent;
     c1ComboBox1.PreValidating += C1ComboBox1_PreValidating;

     //setting custom error message
     c1ComboBox1.ErrorInfo.ErrorMessage = "Please enter a Valid value or an Empty value";

     //setting custom button to clear the selection directly instead of manually deleting the text
     c1ComboBox1.ButtonsSettings.CustomButton.Visible = true;
     var resources = new ResourceManager(typeof(Form1));
     var image = (Bitmap)resources.GetObject("cross (1)");
     c1ComboBox1.ButtonsSettings.CustomButton.Image = image;
     c1ComboBox1.CustomButtonClick += C1ComboBox1_CustomButtonClick;
 }

 private void C1ComboBox1_PreValidating(object sender, PreValidationEventArgs e)
 {
     //only validate if entered text is either from ItemsDataSource or an empty string
     var possibleValues = (sender as C1ComboBox).ItemsDataSource as List<string>;
     if (e.Text == string.Empty || possibleValues.Contains(e.Text))
         e.Succeeded = true;
     else
         e.Succeeded = false;
 }

 private void C1ComboBox1_CustomButtonClick(object sender, EventArgs e)
 {
     //set text to empty
     c1ComboBox1.Text = string.Empty;
 }

 private void button1_Click(object sender, EventArgs e)
 {
     //for testing the working of ComboBox
     Debug.WriteLine("Value: " + c1ComboBox1.Value.ToString() + ", Text: " + c1ComboBox1.Text);
 }