Determine if form is closing in textbox Validating event

J

JR

Hello,

I have a textbox in a form in which I would like to validate the user data.
If it is too long I want to pop up a messagebox. Here is the code:

private void txtDesc_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
if (txtDesc.Text.Length > 60)
{
MessageBox.Show("Please enter a description of 60 characters or
less", "Error");
}
}


The problem is if the user enters text greater than 60 characters and then
clicks on the 'X' to close the form, this event fires and a messagebox still
pops up. I would like to determine if the form is closing when this event
fires and suppress the messagebox. I have tried working with the form's
Closing event and Focused property to no avail.

Any help appreciated.

Thanks.

JR
 
I

Imran Koradia

The problem is if the user enters text greater than 60 characters and then
clicks on the 'X' to close the form, this event fires and a messagebox
still
pops up. I would like to determine if the form is closing when this event
fires and suppress the messagebox. I have tried working with the form's
Closing event and Focused property to no avail.

I guess thats because the Control.Validating event is fired before the
Closing event of the form. One way would be to intercept the WM_CLOSE
message in the WndProc method. Here's how you migth go about this (its in
VB - shouldn't be a problem converting to C#) :

Private mbClosing as Boolean = False

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Const WM_CLOSE As Integer = &H10
Select Case m.Msg
Case WM_CLOSE
Debug.WriteLine("closing")
mbClosing = True
End Select
MyBase.WndProc(m)
End Sub

Private Sub TextBox1_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating
If Not mbClosing Then
'do your validation stuff
End If
End Sub

Because the message is sent as soon you hit the 'x' button, this occurs
before the validating event is fired. Based on boolean mbClosing, you can
then determine whether you want to go ahead with the validation or not.

hope this helps..
Imran.
 

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