Search code examples
vb.netformsformclosing

How to prevent a form from closing without using the FormClosing event


i've recently started studying VB.net with Visual Studio 2010 and so far I'm doing great, but I've been stuck with this problem for several hours now, and after many pages of google and stack overflow searches I come to you.

I have 2 forms, one where you put a persons data and it goes to a database, and another that allows you to search acording to Document Type and Document Number, let's call them Form1 and Form2. Thing is, when the user presses OK on Form 2 and either document or document type are empty a msgbox shows telling them to fill the textbox, but the form closes after that, so what I want to do is to prevent the form from closing if the user presses OK and any field is empty.

My OK button click event on form2 (where i'd like to prevent the form from closing):

Private Sub cmd_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_ok.Click

    If Me.txt_dni.Text = "" Then
        MsgBox("Numero Documento vacio", vbOKOnly + vbCritical, "Atencion")
        Me.txt_dni.Focus()
        Exit Sub
    End If

    If Me.cmb_tdoc.SelectedIndex = -1 Then
        MsgBox("Tipo de Documento vacio", vbOKOnly + vbCritical, "Atencion")
        Me.cmb_tdoc.Focus()
        Exit Sub
    End If

End Sub

Where I get the values from Form2 to its parent, form1; I call this function when I need to look somebody on the datagridview using both document type and document number:

Private Function abrir_form2(ByRef rdoc2 As Integer, ByRef rtdoc2 As Integer)
        Dim dialog As Form2
        Dim doc2 As Integer
        Dim tdoc2 As Integer

dialog = New Form2() Dim result As DialogResult = dialog.ShowDialog(Me) doc2 = dialog.doc2 tdoc2 = dialog.tdoc2 rdoc2 = doc2 rtdoc2 = tdoc2 Return vbNull End Function

Both forms: https://i.sstatic.net/nOf75.png

Maybe there is another way of doing it? Any other way to solve this problem?

Thanks in advance!


Solution

  • My guess is that you have the DialogResult property of that Button set to something other than None. In that case, clicking that Button will assign that same value to the DialogResult property of the form. If the form was displayed using ShowDialog, setting its DialogResult property will close it. If you don't want to close the form every time the Button is clicked then don't set its DialogResult property. Instead, set the DialogResult property of the form explicitly in the Click event of the Button if and only if you want to close the form.