I am working in C# win form application 4.0, where on a form, I am using 3 text boxes, on each text-box, when user enters 'Tab' key then focus jump to next text box.
now on first text-box on validating event I have added some code to check data validity, it connects to database server and takes time of some nano seconds, meanwhile user presses more 'Tab' keys, so that's why my focus shifts on 3rd or 4th text box, it didn't jump on second text box.
Please guide me how resolve this problem. how to ignore this key strokes.
I need a solution where user interface will be suspended until validating event is not performed.
First, there is no reason to send the TAB key. Simply set Focus
on the textbox you want to have focus.
What you want to do is listen to OnKeyDown
for the textbox or control you have focus on at the time you want the enter key to be ignored. By setting e.Handled
to true
, the key press will be ignored.
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (bIgnoreInput)
e.Handled = true;
}
Edit:
I would suggest having a button press to trigger the validation instead of just when the text changes (if that is what you are doing as it is not very clear). That way you can handle the validation and provide user feedback (such as a progress bar or waiting animation).
If you don't want any input at all, set Enabled
to false
on the text boxes until you are done handling the code. When a control is not enabled, no events are triggered. Please be sure to also check InvokeRequired
and Invoke
if it is.
void ValidateInput()
{
SetisValidatingState(true);
System.Threading.Thread workThread = new System.Threading.Thread(delegate()
{
////
// Validate here
////
SetisValidatingState(false);
});
workThread.Start();
}
delegate void SetisValidatingStateDelegate(bool state);
void SetisValidatingState(bool state)
{
if (InvokeRequired)
{
Invoke(new SetisValidatingStateDelegate(SetisValidatingState), new object[] { state });
return;
}
textBox1.AcceptsTabs = textBox2.AcceptsTabs = textBox3.AcceptsTabs = textBox4.AcceptsTabs = !state; // Disable tab while validating = true
progressBar.visible = state; // show progress while validating = true
}