user3051677 user3051677 - 1 year ago 71 Question

Preventing Form From Closing after invalid data asserted

I have a FormClosing Event Handler that upon action Shows a MessageBox with Two Buttons Yes Or No.
So if the user Clicks yes then it Checks values using a For loop and upon finding a invalid value How it SHOULD STAY ON THIS SAME FORM WITHOUT OPENING NEW ONE WITH ALL VALUSE RETAINED.

How can I accomplish this.

Simplified Code is as Shown:
(The class code resides in EditDataForm.vb That is Used by MainForm.vb Clas Code)

''' Closing Event that fired upon user closing the Form
Private Sub EditDataForm_FormClosing(sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing

If MessageBox.Show(Me, "Do you want to save your changes?", "Unsaved Changes!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.Yes Then
ButtonSave_Click(Me, e)
Exit Sub 'Exit this Sub

End If
End Sub

''' Button Save Click Event
Private Sub ButtonSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSave.Click

Dim rowIndex As Integer
Dim CheckDouble As Double

'' Leave the oth and 1th row
For rowIndex = 2 To masterDataGridView.RowCount - 1

If TypeOf(masterDataGridView.Rows(rowIndex).Cells("Val").Value) is String Then

Double.TryParse(masterDataGridView.Rows(rowIndex).Cells("Val").Value, CheckDouble)
If(CheckDouble <= 0) Then
MsgBox("Decimal Number Expect in place of:" & masterDataGridView.Rows(rowIndex).Cells("Val").Value & "at Row Number:" & rowIndex + 1, MsgBoxStyle.Critical, "FAILURE")

Exit Sub
End If
End If


''Other Save Methods etc...

End Sub

Answer Source

In the FormClosing eventhandler, set the Cancel property of the FormClosingEventArgs parameter to true.

It will prevent the form from closing:

In order to integrate this in your application, I would create a method which validates your user-input.
This method should return something (a boolean for instance) which you can use to determine whether or not the data on your form is valid.

Use this method in the formclosing eventhandler, and verify there if the form should be closed or not:

Private Sub EditDataForm_FormClosing(sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing

    If IsFormDataValid() == False Then

       e.Cancel = true;
       Exit Sub 
    End if

End Sub

Private Function IsFormDataValid() As Boolean

    ' Verify input, return true if data is valid; otherwise false.
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download