Validating/Focus problem

P

Paolo Pagano

I have a Form with two TextBox's, I validate first one:

private void textBox1_Validating( object sender, CancelEventArgs e )
{

if( String.IsNullOrEmpty( textBox1.Text ) )
{
DialogResult res = MessageBox.Show( "Retry?", "Error: empty
value",
MessageBoxButtons.RetryCancel
);

e.Cancel = ( res == DialogResult.Retry );
}
}


Pressing "Retry" button, we can correct the value; the problem is that
second TextBox
reives Focus after validation method! (raising unwanted application logic);

This seems due to "MessageBox.Show" (setting 'e.Cancel = true' without
MessageBox.Show
works correctly)

Why this? Am I missing something?
Thank you.
 
C

ClayB

Using VS2005, I tried putting 2 textboxes on a form with the first
textbox having a validating event handler with your code in it. This
seems to work as expected for me. When I click the retry button, the
focus goes back to textbox1.

What version of .NET are you using?

===================================
Clay Burch
Syncfusion, Inc.
 
P

Paolo Pagano

That's true, but try listening the 'GotFocus' event of textBox2, it is
raised (just for a while!) BEFORE
focus goes back to textbox1! Macroscopic beheviour is correct, but this
unwanted GotFocus
can be really problematic!
 
C

ClayB

I do see the behavior that you described. You might be able to avoid
the problem by adding a form-level switch that indicates whether to
ignore the GotFocus, setting the switch in your validate code. In your
GotFocus, you can conditionally execute the event code.

=================
Clay Burch
Syncfusion, Inc.



private bool ignoreGotFocus = true;

void textBox2_GotFocus(object sender, EventArgs e)
{
if (!ignoreGotFocus)
{
Console.WriteLine("textBox2_GotFocus");
}
}

private void textBox1_Validating(object sender, CancelEventArgs e)
{
if( String.IsNullOrEmpty( textBox1.Text ) )
{
ignoreGotFocus = true;
DialogResult res = MessageBox.Show( "Retry?", "Error: empty
value",

MessageBoxButtons.RetryCancel );
ignoreGotFocus = false;
e.Cancel = ( res == DialogResult.Retry );
}
}
 
P

Paolo Pagano

yes, this make me able to skip my got focus logics (thank you) with things
like:

protected override OnGotFocus( EventArgs e )
{
if( isValidating )
return;

base.GotFocus( e );
}

but if the 'skipping' control is (say) a TextBox, this doesn't avoid a rapid
and annoying
text selection flicker (you can see that repeating a 'Retry' on textBox1
after setting textBox2
Text with, say, "blahblahblah" and selecting all;
any idea?
 

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