validating and e.Cancel = true

M

Martijn Boland

Hi all

I put multiple textboxes on a form and assigned a Validating event handler
to them (the same handler for all textboxes). In the event handler I check
if the Text property is empty. If so, I set e.Cancel to true
(CancelEventArgs), to cancel all further actions.

The problem is however that e.Cancel doesn't seem to work. For instance when
tapping on another textbox the Validating event is fired and e.Cancel is set
to true (as expected) but everything continues just af if nothing happened.
The tapped textbox gets focus and should not be the case! Then I tried to
force the focus back to the original textbox (after setting e.Cancel = true)
and guess what: BOOM! Yep the validating event of the tapped textbox was
also fired after setting focus back to the original textbox, resulting in an
infinite loop.

Now I wonder, am I doing something wrong, or is this a nasty bug in the
framework?

Thnx, Martijn
 
M

Maarten Struys

To be honest I don't know why the behavior of the validating event is how
you described it. I verified it with the same result. Here is a simple
workaround. Just forget about setting e.Cancel but use a boolean variable
that you define yourself. If a textbox is empty, set the variable and change
the focus back to the control. Otherwise reset the variable. Here is a code
snippet:

private void textBox_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Text == "" && ! flagReturnFocus)
{
flagReturnFocus = true;
MessageBox.Show("Textbox must contain text");
tb.Focus();
}
else
{
flagReturnFocus = false;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top