I have a WinForms Form with a Textbox and a ComboBox and several other controls. The user can type a search string in the textbox and then the combo box is filtered based on the search string. The Filtering method fires on the Text Changed event of the Textbox.
When the user types text into the textbox, the DroppedDown property of the combo box is set to true so that the combo box opens and the user can see the items as they are being filtered.
This all works great.
It is possible for the user to type in a filter string which results in the combo box being empty. This is where the problem comes in. There has to be at least 1 valid item in the combo box. So, what I would like to do is this:
If the textbox loses focus, I want to use the validating event to check if there is at least one item in the combo box. If not, alert the user and cancel so that the focus remains in the textbox.
The problem is that something weird is happening if I click on the form that contains the textbox and there are no items in that combo box. I get a very non-descriptive error message on the parent form that launched the form that I am working on.
QueryDesignerTool qdTool = new QueryDesignerTool();
DialogResult dr = qdTool.ShowDialog(this);
I get
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'index'.
While the code is running, if I inspect qdTool and look at the combo box in question, I can see that the SelectedIndex of the combo box is 0 and the count of items is 0, which is illegal.
I am not sure why it is erroring out and falling back to the parent form. But that is not why I am asking for help.
What I am interested in is validating the text in the textbox if the user clicks out of it. I have read that focus cannot be passed to a form, so the Leave Focus event will not fire and hence the Validating event will not fire if focus is on the text box and then the user clicks the form.
So then, is the proper course of action then to catch the click event for the form and handle the validation of that text box?
What I have tried:
I have described what I have tried in the problem description.