tags:

views:

336

answers:

2

I'm converting a VB6 application to Winforms and in VB6 we frequently use a technique where certain textboxes are only made visible when specific values are entered in prior a textbox.

The problem is that the decision to make the textbox visible is only made in the Validating event at which point the next control to gain focus has already been determined. When we make the dependent textbox visible, the focus has already skipped over the control.

We were able to solve the problem in VB6 by placing an empty,transparent usercontrol between the two textboxes and in the usercontrol's gotfocus event stuff an extra TAB in the keyboard buffer. Surprisingly it works quite well. It even works when you shift-tab back. For some reason, the usercontrol is ignored and focus returns to the first textbox. Unsurprisingly, I'm hoping there is a better solution in Winforms.

Has anyone successfully dealt with this situation?

A: 

I believe that you'll find that things "just work" in WinForms.

The Validat*ing* event is triggered before any decision is made about which field should receive the focus - this allows the event to force focus back to the original control if validation fails.

Have a look at the details of the Control.Validating Event from MSDN to see which events are triggered in which order.

Alternatively, perhaps the Validating event is too late in the workflow - have you considered disclosing the controls as soon as the value in the relevant field is suitable, without waiting for focus to change? I've done this - though only with checkboxes - and the User Experience was ideal.

Bevan
Checkboxes work because it is a binary value and you can take action as soon as the user checks the box. With Textboxes however you really need the complete input before the you can make the decision as to whether the next field should be made visible. The next control to gain focus is definitely determined before the validating event occurs. I have a solution that works in every case except when you shift-tab and a field becomes visible. I'll post it later today.
Darrel Miller
+1  A: 

I had a similar issue on a winform application where I needed a textbox that was hidden to be shown based on the previous control's value while putting the control in the tab order so that it would get focus. My initial solution was to setup a class level variable that would be used in conjunction with GotFocus and LostFocus (or Enter/Exit) on the 2 controls to determine if focus was lost from the previous control and force set the focus to the next control. This isn't a reliable solution but is still an option.

My current solution works much better though. I needed to put a search button for the initial control. This button was in the tab order between the 2 controls. Because the button would take focus from the first control, it would give the second control time to show itself when the first control validated.

Hope this helps.

Chris Porter