PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2012 messagebox cancel button closes form-VBForums
Results 1 to 9 of 9

Thread: messagebox cancel button closes form

  1. #1

    Thread Starter
    Member G33kman's Avatar
    Join Date
    Nov 2009
    Location
    Mankato, MN
    Posts
    40

    Question messagebox cancel button closes form

    Ok so I am trying to make it so that when my form closes and there is text in any of the text boxes it will ask you to save. I have most of it worked out but whenever I click cancel it either keeps popping up the same messagebox repeatedly otherwise if I click "yes" to open the savefiledialog and then select "cancel" and than "cancel" on the message box again it closes the program.
    I'd like it to just return to the main form...

    Here's the code that I have (I wasn't sure where the problem is exactly so here's all the code for the form...) I do know it won't let me e.cancel = true for the cancel button it throws an error.

    Code:
    Imports System.IO
    
    Public Class mainWindow
    
        Private Sub checkTextBoxes(e As System.ComponentModel.CancelEventArgs)                                           'THIS IS PART OF THE PROBLEM
    
            'Declare the variables
            Dim ctrl As Control
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
    
            'Check all the text boxes
            For Each ctrl In Me.Controls
                If (TypeOf ctrl Is TextBox) Then
                    If ctrl.Text <> "" Then
    
                        'Set sfdmainWindow properties
                        With sfdmainWindow
                            .DefaultExt = "rei"
                            .FileName = firstName & " " & lastName & " " & "-" & " " & Today()
                            .Filter = "Reichel Lead Log File (*.rei) | *.rei"
                            .FilterIndex = 1
                            .OverwritePrompt = True
                            .Title = "Reichel Insulation - Lead Log"
                        End With
    
                        'Declare variables
                        Dim msg As String
                        Dim title As String
                        Dim style As MsgBoxStyle
                        Dim response As MsgBoxResult
    
                        msg = "Would you like to save before quitting?"   ' Define message.
                        style = MsgBoxStyle.DefaultButton3 Or MsgBoxStyle.Question Or MsgBoxStyle.YesNoCancel
                        title = "Reichel Insulation - Lead Log"   ' Define title.
                        ' Display message.
                        response = MsgBox(msg, style, title)
    
                        If response = MsgBoxResult.Yes Then
                            sfdmainWindow.ShowDialog()
                        End If
                        If response = MsgBoxResult.No Then
                            End
                        End If
                        If response = MsgBoxResult.Cancel Then
                            e.Cancel = True                                                                     'THIS IS PART OF THE PROBLEM
                        End If
                    End If
                End If
            Next ctrl
        End Sub
    
        'INSERT TOOLTIPS ON FORM
        Private Sub ToolTips()
            Me.toolTmainWindow.SetToolTip(Me.cbxRep, "Who is the sales rep that will handle this customer estimate?")
            Me.toolTmainWindow.SetToolTip(Me.cbxJobType, "What is the main job type for this estimate?")
            Me.toolTmainWindow.SetToolTip(Me.cbxSource, "Where did the customer hear about us?")
            Me.toolTmainWindow.SetToolTip(Me.txtSource, "If the customer heard about us from a source" & ControlChars.NewLine & "other than what's listed please enter it here.")
            Me.toolTmainWindow.SetToolTip(Me.txtFirstName, "What is the Customers first name?")
            Me.toolTmainWindow.SetToolTip(Me.txtLastName, "What is the Customer last name?")
            Me.toolTmainWindow.SetToolTip(Me.txtAddress1, "What is the customers address?")
            Me.toolTmainWindow.SetToolTip(Me.txtAddress2, "What is the customers city?")
            Me.toolTmainWindow.SetToolTip(Me.txtZipCode, "What is the customers zip code?")
            Me.toolTmainWindow.SetToolTip(Me.cbxState, "What is the customers state?")
            Me.toolTmainWindow.SetToolTip(Me.txtBusinessName, "What is the name of the customers business name?")
            Me.toolTmainWindow.SetToolTip(Me.txtEmail, "What is the customers email address?")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeHour, "Enter the hour that the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeMinute, "Enter the minute range that the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeAMPM, "Enter the AM/PM when the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.txtComments, "Please fill out as much information about the job that we will be bidding" & ControlChars.NewLine & "along with any additional jobs that will be doing")
        End Sub
    
        'CLEAR THE TEXT BOXES ON THE FORM
        Private Sub ResetForm(ByVal root As Control)
            For Each ctrl As Control In root.Controls
                ResetForm(ctrl)
                If TypeOf ctrl Is TextBox Then
                    CType(ctrl, TextBox).Text = String.Empty
                End If
                If TypeOf ctrl Is ComboBox Then
                    CType(ctrl, ComboBox).Items.Clear()
                End If
            Next
            monCalendar.SelectionStart = Today
        End Sub
    
        'WHAT HAPPENS WHEN THE FORM CLOSES
        Private Sub mainWindow_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            checkTextBoxes()                                                                                                                                             'THIS IS PART OF THE PROBLEM
        End Sub
    
        'WHAT HAPPENS WHEN THE MAIN FORM LOADS
        Private Sub mainWindow_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'Show the startWindow form
            startWindow.ShowDialog()
            ToolTips()
        End Sub
    
        'WHAT HAPPENS WHEN THE SAVE BUTTON IS CLICKED
        Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    
            'Set Variables
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
    
            'Set sfdmainWindow properties
            With sfdmainWindow
                .DefaultExt = "rei"
                .FileName = firstName & " " & lastName & " " & "-" & " " & Today()
                .Filter = "Reichel Lead Log File (*.rei) | *.rei"
                .FilterIndex = 1
                .OverwritePrompt = True
                .Title = "Reichel Insulation - Lead Log"
            End With
    
            'Save the file
            sfdmainWindow.ShowDialog()
        End Sub
    
        'WHAT HAPPENS WHEN THE SOURCE COMBO BOX ITEM IS CHANGED
        Private Sub cbxSource_SelectedValueChanged(sender As Object, e As EventArgs) Handles cbxSource.SelectedValueChanged
            If cbxSource.SelectedItem = "Other" Then
                txtSource.Enabled = True
            Else
                txtSource.Enabled = False
            End If
        End Sub
    
        'WHAT HAPPENS WHEN THE CANCEL BUTTON IS CLICKED
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            checkTextBoxes()                                                                                                                  'THIS IS PART OF THE PROBLEM
        End Sub
    
        'WHAT HAPPENS WHEN THE HOUR SELCTION IS CHANGED
        Private Sub cbxTimeHour_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTimeHour.SelectedIndexChanged
            cbxTimeMinute.Enabled = True
        End Sub
    
        'WHAT HAPPENS WHEN THE MINUTE SELECTION IS CHANGED
        Private Sub cbxTimeMinute_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTimeMinute.SelectedIndexChanged
            cbxTimeAMPM.Enabled = True
        End Sub
    
        'RESET THE FORM TO THE DEFAULTS BY CLICKING THE FILE-NEW ITEM
        Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
    
            'Clear the textboxes
            ResetForm(Me)
    
            'Set the focus to the Sales Rep ComboBox
            cbxRep.Focus()
        End Sub
    
        'ENABLE THE SAVE BUTTON --- TEXTBOX FIRST NAME
        Private Sub txtFirstName_TextChanged(sender As Object, e As EventArgs) Handles txtFirstName.TextChanged, txtLastName.TextChanged
            If txtFirstName.TextLength = 0 Then
                btnSave.Enabled = False
            Else
                btnSave.Enabled = True
            End If
        End Sub
    
        'OPEN FILE DIALOG MENU STRIP
        Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
            ofdmainWindow.ShowDialog()
        End Sub
    
        'SAVE FILE DIALOG MENU STRIP
        Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
            sfdmainWindow.ShowDialog()
        End Sub
    
        'EXIT PROGRAM MENU STRIP
        Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
            checkTextBoxes()                                                                                                                                   'THIS IS PART OF THE PROBLEM
        End Sub
    End Class

  2. #2
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,313

    Re: messagebox cancel button closes form

    Considering you have put your save dialog inside a loop what do you expect? It will keep looping until while the textbox loop is true.

  3. #3

    Thread Starter
    Member G33kman's Avatar
    Join Date
    Nov 2009
    Location
    Mankato, MN
    Posts
    40

    Re: messagebox cancel button closes form

    Quote Originally Posted by ident View Post
    Considering you have put your save dialog inside a loop what do you expect? It will keep looping until while the textbox loop is true.
    Oh hey that might be an issue... Ok I'll try and get that straightened out. But what about the cancel button closing the program? I can't put the e.Cancel = True in there because it errors out... :/

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,382

    Re: messagebox cancel button closes form

    well... at least you've correctly identified where part of the problem lies:
    Code:
        'WHAT HAPPENS WHEN THE CANCEL BUTTON IS CLICKED
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            checkTextBoxes()                                                                                                                  'THIS IS PART OF THE PROBLEM
        End Sub
    And the reason is because you're not telling the process to cancel the form closing...

    actually... I'm a little... ne... A LOT surprised it even compiles... checkTextBoxes requires a parameter to be passed in... which you clearly don't do...

    also System.ComponentModel.CancelEventArgs isn't the same as FormClosingEventArgs .. which is part of the System.Windows.Forms namespace...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  5. #5
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,313

    Re: messagebox cancel button closes form

    vb Code:
    1. Public Class mainWindow
    2.  
    3.     Private Sub mainWindow_FormClosing(ByVal sender As Object,
    4.                                        ByVal e As FormClosingEventArgs) Handles Me.FormClosing
    5.         ' Check for any textboxs that contain information.
    6.         Dim isNotEmptyTextBoxs As Boolean = Me.Controls.OfType(Of TextBox).Any(Function(tb) tb.Text.Trim <> String.Empty)
    7.  
    8.         If isNotEmptyTextBoxs Then
    9.             Dim result As DialogResult = PromptForApplicationContinue()
    10.  
    11.             If result = DialogResult.Yes Then
    12.                 ' Handle saving...
    13.             ElseIf result = DialogResult.Cancel Then
    14.                 e.Cancel = True
    15.             End If
    16.         End If                                                                                                                                           'THIS IS PART OF THE PROBLEM
    17.     End Sub
    18.  
    19.     Private Function PromptForApplicationContinue() As DialogResult
    20.         Dim message As String = String.Format("Do you wish to save your work?{0}{0}Please Cancel to stop application from closing.",
    21.                                                Environment.NewLine)
    22.         Dim result As DialogResult = MessageBox.Show(message,
    23.                                                      Application.ProductName,
    24.                                                      MessageBoxButtons.YesNoCancel,
    25.                                                      MessageBoxIcon.Question,
    26.                                                      MessageBoxDefaultButton.Button1)
    27.         Return result
    28.     End Function
    29.  
    30. End Class

  6. #6

    Thread Starter
    Member G33kman's Avatar
    Join Date
    Nov 2009
    Location
    Mankato, MN
    Posts
    40

    Re: messagebox cancel button closes form

    Yeah I was kinda wondering that myself I'm not an experienced VB.net programmer by any means but the only way I'm gonna get it down is by trial and error.
    I knew that the two different EventArgs were why it was throwing the error but I guess I'm not understanding how to fix it. Normally I do as much searching as I can on google but I'm not really sure how to word this one...

    I changed the code so that the save file dialog is out of the loop now but I still can't cancel (obviously cause I haven't changed any of that issue yet)

    Here's the updated chunk of code.

    Code:
    Private Sub checkTextBoxes()
    
            'Declare the variables
            Dim ctrl As Control
            Dim blnCtrl As Boolean
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
            Dim msg As String
            Dim title As String
            Dim style As MsgBoxStyle
            Dim response As MsgBoxResult
    
            'Check all the textboxes
            For Each ctrl In Me.Controls
                If (TypeOf ctrl Is TextBox) Then
                    If ctrl.Text <> "" Then
                        blnCtrl = True
                    End If
                End If
            Next
            If blnCtrl = True Then
                msg = "Would you like to save before quitting?"   ' Define message.
                style = MsgBoxStyle.DefaultButton3 Or MsgBoxStyle.Question Or MsgBoxStyle.YesNoCancel
                title = "Reichel Insulation - Lead Log"   ' Define title.
                ' Display message.
                response = MsgBox(msg, style, title)
    
                If response = MsgBoxResult.Yes Then
                    sfdmainWindow.ShowDialog()
                End If
                If response = MsgBoxResult.No Then
                    End
                End If
            End If
        End Sub

  7. #7
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,313

    Re: messagebox cancel button closes form

    Read this last line again posted above.... also System.ComponentModel.CancelEventArgs isn't the same as FormClosingEventArgs .. which is part of the System.Windows.Forms namespace...

    vb Code:
    1. Public Class mainWindow
    2.  
    3.     Private Sub mainWindow_FormClosing(ByVal sender As Object,
    4.                                        ByVal e As FormClosingEventArgs) Handles Me.FormClosing
    5.         'e (FormClosingEventArgs)
    6.         e.Cancel = True
    7.     End Sub
    8.  
    9.     Private Sub checkTextBoxes()
    10.         ' FormClosingEventArgs ?????
    11.     End Sub
    12.  
    13. End Class

    Oh and dont ever use END to close an application.

  8. #8

    Thread Starter
    Member G33kman's Avatar
    Join Date
    Nov 2009
    Location
    Mankato, MN
    Posts
    40

    Re: messagebox cancel button closes form

    Ok so I'm trying to follow along with what you're telling (and showing) me sorry if this is frustrating but when you post clips of code I read through it and than look at my code to see the difference and try and make changes. Everything works now other than when I click the cancel button on the save file dialog... :/

    Here's the complete code that I have now. Could you at least let me know if I'm getting "close" to what you're trying to tell me to do?
    I don't want you to hold my hand through this (otherwise I won't learn anything) so I hope you don't feel like I'm asking for that. I just want to understand how this stupid cancel button is suppose to return to the main window form.

    EDIT "Added in what I changed:
    I did change the END to Close()
    I don't remember if I changed anything else for sure as I was going through and switching things back and forth so much...


    Code:
    Imports System.IO
    
    Public Class mainWindow
    
        Private Sub checkTextBoxes()
    
            'Declare the variables
            Dim ctrl As Control
            Dim blnCtrl As Boolean
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
            Dim msg As String
            Dim title As String
            Dim style As MsgBoxStyle
            Dim response As MsgBoxResult
    
            'Check all the textboxes
            For Each ctrl In Me.Controls
                If (TypeOf ctrl Is TextBox) Then
                    If ctrl.Text <> "" Then
                        blnCtrl = True
                    End If
                End If
            Next
            If blnCtrl = True Then
                msg = "Would you like to save before quitting?"   ' Define message.
                style = MsgBoxStyle.DefaultButton3 Or MsgBoxStyle.Question Or MsgBoxStyle.YesNoCancel
                title = "Reichel Insulation - Lead Log"   ' Define title.
                'Display Message
                response = MsgBox(msg, style, title)
    
                If response = MsgBoxResult.Yes Then
                    sfdmainWindow.ShowDialog()
                End If
                If response = MsgBoxResult.No Then
                    Close()
                End If
            End If
        End Sub
    
        'INSERT TOOLTIPS ON FORM
        Private Sub ToolTips()
            Me.toolTmainWindow.SetToolTip(Me.cbxRep, "Who is the sales rep that will handle this customer estimate?")
            Me.toolTmainWindow.SetToolTip(Me.cbxJobType, "What is the main job type for this estimate?")
            Me.toolTmainWindow.SetToolTip(Me.cbxSource, "Where did the customer hear about us?")
            Me.toolTmainWindow.SetToolTip(Me.txtSource, "If the customer heard about us from a source" & ControlChars.NewLine & "other than what's listed please enter it here.")
            Me.toolTmainWindow.SetToolTip(Me.txtFirstName, "What is the Customers first name?")
            Me.toolTmainWindow.SetToolTip(Me.txtLastName, "What is the Customer last name?")
            Me.toolTmainWindow.SetToolTip(Me.txtAddress1, "What is the customers address?")
            Me.toolTmainWindow.SetToolTip(Me.txtAddress2, "What is the customers city?")
            Me.toolTmainWindow.SetToolTip(Me.txtZipCode, "What is the customers zip code?")
            Me.toolTmainWindow.SetToolTip(Me.cbxState, "What is the customers state?")
            Me.toolTmainWindow.SetToolTip(Me.txtBusinessName, "What is the name of the customers business name?")
            Me.toolTmainWindow.SetToolTip(Me.txtEmail, "What is the customers email address?")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeHour, "Enter the hour that the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeMinute, "Enter the minute range that the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.cbxTimeAMPM, "Enter the AM/PM when the customer called.")
            Me.toolTmainWindow.SetToolTip(Me.txtComments, "Please fill out as much information about the job that we will be bidding" & ControlChars.NewLine & "along with any additional jobs that will be doing")
        End Sub
    
        'CLEAR THE TEXT BOXES ON THE FORM
        Private Sub ResetForm(ByVal root As Control)
            For Each ctrl As Control In root.Controls
                ResetForm(ctrl)
                If TypeOf ctrl Is TextBox Then
                    CType(ctrl, TextBox).Text = String.Empty
                End If
                If TypeOf ctrl Is ComboBox Then
                    CType(ctrl, ComboBox).Items.Clear()
                End If
            Next
            monCalendar.SelectionStart = Today
        End Sub
    
        'WHAT HAPPENS WHEN THE FORM CLOSES
        Private Sub mainWindow_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
            ' Check for any textboxes that contain information.
            Dim isNotEmptyTextBoxs As Boolean = Me.Controls.OfType(Of TextBox).Any(Function(tb) tb.Text.Trim <> String.Empty)
    
            If isNotEmptyTextBoxs Then
                Dim result As DialogResult = PromptForApplicationContinue()
    
                If result = DialogResult.Yes Then
                    sfdmainWindow.ShowDialog()
                ElseIf result = DialogResult.Cancel Then
                    e.Cancel = True
                End If
            End If                                                                                                                                           'THIS IS PART OF THE PROBLEM
        End Sub
    
        'PROMPT FOR THE APPLICATION TO CONTINUE
        Private Function PromptForApplicationContinue() As DialogResult
            Dim message As String = String.Format("Do you wish to save your work?{0}{0}Please Cancel to stop application from closing.", Environment.NewLine)
            Dim result As DialogResult = MessageBox.Show(message, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
            Return result
        End Function
    
        'WHAT HAPPENS WHEN THE MAIN FORM LOADS
        Private Sub mainWindow_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'Show the startWindow form
            startWindow.ShowDialog()
            ToolTips()
        End Sub
    
        'WHAT HAPPENS WHEN THE SAVE BUTTON IS CLICKED
        Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    
            'Set Variables
            Dim firstName As String = txtFirstName.Text
            Dim lastName As String = txtLastName.Text
    
            'Set sfdmainWindow properties
            With sfdmainWindow
                .DefaultExt = "rei"
                .FileName = firstName & " " & lastName & " " & "-" & " " & Today()
                .Filter = "Reichel Lead Log File (*.rei) | *.rei"
                .FilterIndex = 1
                .OverwritePrompt = True
                .Title = "Reichel Insulation - Lead Log"
            End With
    
            'Save the file
            sfdmainWindow.ShowDialog()
        End Sub
    
        'WHAT HAPPENS WHEN THE SOURCE COMBO BOX ITEM IS CHANGED
        Private Sub cbxSource_SelectedValueChanged(sender As Object, e As EventArgs) Handles cbxSource.SelectedValueChanged
            If cbxSource.SelectedItem = "Other" Then
                txtSource.Enabled = True
            Else
                txtSource.Enabled = False
            End If
        End Sub
    
        'WHAT HAPPENS WHEN THE CANCEL BUTTON IS CLICKED
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            checkTextBoxes()
        End Sub
    
        'WHAT HAPPENS WHEN THE HOUR SELCTION IS CHANGED
        Private Sub cbxTimeHour_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTimeHour.SelectedIndexChanged
            cbxTimeMinute.Enabled = True
        End Sub
    
        'WHAT HAPPENS WHEN THE MINUTE SELECTION IS CHANGED
        Private Sub cbxTimeMinute_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTimeMinute.SelectedIndexChanged
            cbxTimeAMPM.Enabled = True
        End Sub
    
        'RESET THE FORM TO THE DEFAULTS BY CLICKING THE FILE-NEW ITEM
        Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
    
            'Clear the textboxes
            ResetForm(Me)
    
            'Set the focus to the Sales Rep ComboBox
            cbxRep.Focus()
        End Sub
    
        'ENABLE THE SAVE BUTTON --- TEXTBOX FIRST NAME
        Private Sub txtFirstName_TextChanged(sender As Object, e As EventArgs) Handles txtFirstName.TextChanged, txtLastName.TextChanged
            If txtFirstName.TextLength = 0 Then
                btnSave.Enabled = False
            Else
                btnSave.Enabled = True
            End If
        End Sub
    
        'OPEN FILE DIALOG MENU STRIP
        Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
            ofdmainWindow.ShowDialog()
        End Sub
    
        'SAVE FILE DIALOG MENU STRIP
        Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
            sfdmainWindow.ShowDialog()
        End Sub
    
        'EXIT PROGRAM MENU STRIP
        Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
            checkTextBoxes()
        End Sub
    End Class
    Last edited by G33kman; Jun 25th, 2013 at 04:15 PM. Reason: Forgot to add in some info about what I changed.

  9. #9
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,313

    Re: messagebox cancel button closes form

    A few pieces of advice. Don't post full classes where code is not needed.Only post the code that's being discussed. Make comments meaning full. Your comments are very OTT and pointless. "Check all the textboxes" the code is obvious here. Finally i noticed you removed some of the white spaces i added in my code. I would advise to keep code on the screen. It's cleaner. Back in the old days we had small monitors. Your program wont perform any different forcing long lines of code.

    Ok looking at checkTextBoxes() We have tried to nude you on FormClosedEventArgs but you seem to choose to ignore the signature needed. Private Sub checkTextBoxes() has no signature. Now pay attention to form close signature.

    Code:
    Private Sub mainWindow_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
    e As System.Windows.Forms.FormClosingEventArgs

    Are you passing this argument to checkTextBoxes? No. Next you decide to loop all the textboxs checking each textboxs value even if you know One contains text. Why?

    vb Code:
    1. 'Check all the textboxes
    2. For Each tb In Me.Controls.OfType(Of TextBox)()
    3.      If tb.Text.Trim <> String.Empty Then
    4.         ' Information stored
    5.         blnCtrl = True : Exit For
    6.      End If
    7. Next

    vb Code:
    1. Imports System.IO
    2.  
    3. Public Class mainWindow
    4.  
    5.     Private Sub mainWindow_FormClosing(ByVal sender As Object,
    6.                                        ByVal e As System.Windows.Forms.FormClosingEventArgs
    7.                                        ) Handles Me.FormClosing
    8.         checkTextBoxes(e)
    9.     End Sub
    10.  
    11.     Private Sub checkTextBoxes(ByVal e As FormClosingEventArgs)
    12.         Dim isNotEmptyTextBoxs As Boolean = Me.Controls.OfType(Of TextBox).Any(Function(tb) tb.Text.Trim <> String.Empty)
    13.  
    14.         If isNotEmptyTextBoxs Then
    15.             Dim result As DialogResult = PromptForApplicationContinue()
    16.  
    17.             If result = DialogResult.Yes Then
    18.                 ' Handle saving
    19.                 sfdmainWindow.ShowDialog()
    20.             ElseIf result = DialogResult.Cancel Then
    21.                 e.Cancel = True
    22.             End If
    23.         End If
    24.     End Sub
    25.  
    26.     Private Function PromptForApplicationContinue() As DialogResult
    27.         Dim message As String = String.Format("Do you wish to save your work?{0}{0}Please Cancel to stop application from closing.", Environment.NewLine)
    28.         Dim result As DialogResult = MessageBox.Show(message, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
    29.         Return result
    30.     End Function
    31. End Class

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width