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)
Else
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")
'''''''' HOW CAN I STAY ON THIS SAME FORM
Exit Sub
End If
End If
Next
''Other Save Methods etc...
End Sub
答案 0 :(得分:1)
In the FormClosing eventhandler, set the Cancel
property of the FormClosingEventArgs
parameter to true.
It will prevent the form from closing:
https://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs(v=vs.110).aspx
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
SaveData()
End Sub
Private Function IsFormDataValid() As Boolean
' Verify input, return true if data is valid; otherwise false.
End Function