locked
Another message box question ( How can I use two message boxes with one click of a button) RRS feed

  • Question

  • I have a form where a user insert customers name and address, Then select a date, After selecting the date the user clicks a button to save the data to the database. Everything is fine up to now.

    When I click another button to print out the information, How Do I use two message boxes, To check if the Price of Job has been inserted into the textbox (txtPriceOfJob), with the message box Yes/No, Asking if the user has forgotten to enter the price of the job. If the user select message box button Yes Then I the textbox is highlighted so they can put a price in the textbox  (txtPriceOfJob).

    If the user selects No from the message box, then Do nothing.

    I then want to check if a price has been inserted into a Label (lbTotalPartsPrice) and If not, then a second message box saying.... Have you forgotten to enter a parts Price (Yes or No buttons).

    If the user selects Yes then Highlight a textbox called (txtPartPrice1) so the user can insert the price of the part/s...

    The issue I have is getting from the first message box to the second. The code I have now is below...

    Private Sub CmdCreateInvoice_Click(sender As Object, e As EventArgs) Handles CmdCreateInvoice.Click
    
    
            If GetDec((txtPriceOfJob.Text)) = GetDec("0.00") Then
    
                Dim Message1 As String = "Have you forgotten to enter the Price of the job?"
                Dim Caption1 As String = LbUsername.Text & ", There is no Price for Job"
                Dim Buttons1 As MessageBoxButtons = MessageBoxButtons.YesNo
                Dim Result1 As DialogResult
    
                'Displays the MessageBox
                Result1 = MessageBox.Show(Message1, Caption1, Buttons1)
    
                ' Gets the result of the MessageBox display.
                If Result1 = System.Windows.Forms.DialogResult.Yes Then
                    ' Go to TxtPartPrice1
                    CmdUpdate.PerformClick()
                    txtPriceOfJob.Focus()
                ElseIf Result1 = System.Windows.Forms.DialogResult.No Then
                   'Go to the next else 
    
                End If
    
            End If
    
            '<<<<<<<<<<<<<<<<<<< Here is where my issue is >>>>>>>>>>>>>>
            
            
            ElseIf GetDec(lbTotalPartsPrice.Text) = GetDec("0.00") Then
                ' Initializes variables to pass to the MessageBox.Show method.
                Dim Message As String = "Have you forgotten to enter the Price of Parts?" & vbCrLf &
                    vbCrLf & "Click Yes to Add Price of Parts," & 
                    vbCrLf & "Once Prices are Added, 'Click Save Update Button' " &                
                    vbCrLf & vbCrLf & "Else" &
                    vbCrLf & vbCrLf & "Click No to Produce an Invoice without Part Prices"
                Dim Caption As String = LbUsername.Text & ", No Price's have been Added for Parts"
                Dim Buttons As MessageBoxButtons = MessageBoxButtons.YesNo
                Dim Result As DialogResult
    
                'Displays the MessageBox
                Result = MessageBox.Show(Message, Caption, Buttons)
    
                ' Gets the result of the MessageBox display.
                If Result = System.Windows.Forms.DialogResult.Yes Then
                    ' Click CMDUpdate and Go to TxtPartPrice1
                    CmdUpdate.PerformClick()
                    txtPartPrice1.Focus()
    
                ElseIf Result = System.Windows.Forms.DialogResult.No Then
                    'Go to next Else if
                   
    
                End If
             
    
            If GetDec(lbTotalPartsPrice.Text) > GetDec("0.00") AndAlso GetDec((txtPriceOfJob.Text)) > GetDec("0.00") Then
    
    
                UpdateJob2()
                InsertIntoJobCompleted()
                PrintDocument1.Print()
            End If
    
        End Sub

    I hope someone can help 

    Kind Regards

    Gary


    Gary Simpson


    • Edited by Gary Simpson Wednesday, November 18, 2020 7:42 PM
    Wednesday, November 18, 2020 6:53 PM

Answers

  • Hi

    A very brief look at your code.  I seem to see a possible issue with the If .... Else ..... End If blocks. I think there is no proper match for the ElseIf (just below your problem comment) - if I am correct, then try changing the ElseIf to If and see if it will compile.


    Regards Les, Livingston, Scotland


    Hi Les Thank you for getting back to me. I have tried your suggestion. But when the first message box shows and I click yes, I expected to go to the textbox (txtPriceOfJob) So I could insert a price.

    Instead I get the second message box as soon as I click Yes on the first message box.

    Kind Regards

    Gary


    Gary Simpson

    Hi

    OK, here is a try at what *maybe* is required. (I couldn't fully rationalize some of the references in your code)

    	Private Sub CmdCreateInvoice_Click(sender As Object, e As EventArgs) Handles CmdCreateInvoice.Click
    
    		If GetDec((txtPriceOfJob.Text)) = 0D Then
    
    			Dim Message1 As String = "Have you forgotten to enter the Price of the job?"
    			Dim Caption1 As String = LbUsername.Text & ", There is no Price for Job"
    			Dim Buttons1 As MessageBoxButtons = MessageBoxButtons.YesNo
    			Dim Result1 As DialogResult
    
    			Result1 = MessageBox.Show(Message1, Caption1, Buttons1)
    
    			If Result1 = DialogResult.Yes Then
    				' Go to TxtPartPrice1 ????
    				CmdUpdate.PerformClick()
    				txtPriceOfJob.Select()
    				Exit Sub
    			End If
    		End If
    
    		If GetDec(lbTotalPartsPrice.Text) = 0D Then
    			Dim Message As String = "Have you forgotten to enter the Price of Parts?" & vbCrLf &
    								vbCrLf & "Click Yes to Add Price of Parts," &
    								vbCrLf & "Once Prices are Added, 'Click Save Update Button' " &
    								vbCrLf & vbCrLf & "Else" &
    								vbCrLf & vbCrLf & "Click No to Produce an Invoice without Part Prices"
    			Dim Caption As String = LbUsername.Text & ", No Price's have been Added for Parts"
    			Dim Buttons As MessageBoxButtons = MessageBoxButtons.YesNo
    			Dim Result As DialogResult
    
    			Result = MessageBox.Show(Message, Caption, Buttons)
    
    			If Result = DialogResult.Yes Then
    				lbTotalPartsPrice.Select()
    			End If
    		End If
    
    		If GetDec(lbTotalPartsPrice.Text) > 0D AndAlso GetDec((txtPriceOfJob.Text)) > 0D Then
    			UpdateJob2()
    			InsertIntoJobCompleted()
    			PrintDocument1.Print()
    		End If
    
    	End Sub
    	Function GetDec(s As String) As Decimal
    		Dim v As Decimal = 0D
    		If Decimal.TryParse(s, v) Then Return v
    		Return 0D
    	End Function


    Regards Les, Livingston, Scotland

    • Marked as answer by Gary Simpson Wednesday, November 18, 2020 11:41 PM
    Wednesday, November 18, 2020 10:39 PM
  • Even though you have selected a solution and you have asked about mine.

    What mine does for simple example is annotate properties in a class with rules, in this case simple rules but they can get very complex but also still easy to use.

    We have two TextBox controls, one a regular TextBox and the other a NumericTextBox I created.

    Here is the class used to store information from a windows form.

    Public Class Products
        Public Property ProductID As Integer
        <Required(ErrorMessage:="{0} Required")>
        <StringLength(30, MinimumLength:=3, ErrorMessage:="Invalid {0}")>
        Public Property ProductName As String
        <Required(ErrorMessage:="{0} Required")>
        <Range(1, Decimal.MaxValue, ErrorMessage:="Please enter a value bigger than {1} for {0}")>
        Public Property UnitPrice As Decimal
    End Class

    We validate by creating a new instance of Products and pass the class to the validator. The Validate checks property values against annotations as per the first code block. If there is no problem the class instance can be used in a data class (I never write what can be written in a class in a form) to add, edit data in a database.

    Public Class Form1
        Private Sub ValidateButton_Click(sender As Object, e As EventArgs) _
            Handles ValidateButton.Click
    
            Dim product As New Products With {
                    .ProductName = ProductNameTextBox.Text,
                    .UnitPrice = UnitPriceTextBox.AsDecimal}
    
            Dim validationResult As EntityValidationResult = ValidationHelper.ValidateEntity(product)
            If validationResult.HasError Then
                MessageBox.Show(validationResult.ErrorMessageList())
            End If
    
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    • Marked as answer by Gary Simpson Friday, November 20, 2020 6:30 PM
    Thursday, November 19, 2020 1:17 AM

All replies

  • Hi

    A very brief look at your code.  I seem to see a possible issue with the If .... Else ..... End If blocks. I think there is no proper match for the ElseIf (just below your problem comment) - if I am correct, then try changing the ElseIf to If and see if it will compile.


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, November 18, 2020 7:48 PM
    Wednesday, November 18, 2020 7:47 PM
  • Hi

    A very brief look at your code.  I seem to see a possible issue with the If .... Else ..... End If blocks. I think there is no proper match for the ElseIf (just below your problem comment) - if I am correct, then try changing the ElseIf to If and see if it will compile.


    Regards Les, Livingston, Scotland


    Hi Les Thank you for getting back to me. I have tried your suggestion. But when the first message box shows and I click yes, I expected to go to the textbox (txtPriceOfJob) So I could insert a price.

    Instead I get the second message box as soon as I click Yes on the first message box.

    Kind Regards

    Gary


    Gary Simpson

    Wednesday, November 18, 2020 9:12 PM
  • Hello,

    A completely different path is to use data annotations as per my Microsoft TechNet article. The basic idea is to have a class which represents data to save or update and pass an instance of the class to a validator.

    https://social.technet.microsoft.com/wiki/contents/articles/53055.net-defensive-data-programming-part-4-data-annotation.aspx#Windows_Forms_Data_Annotation

    Basic example

    Namespace Sample1
    	Partial Public Class Form1
    		Inherits Form
    
    		Private ReadOnly _bsContacts As New BindingSource()
    		Private _dataGridViewSizeDone As Boolean
    		Public Sub New()
    			InitializeComponent()
    		End Sub
    		Private Sub ValidateSingleContactButton_Click(ByVal sender As Object, ByVal e As EventArgs)
    			Dim contact() As New Contact() With {
    				.FirstName = FirstNameTextBox.Text,
    				.LastName = LastNameTextBox.Text,
    				.PersonalEmail = PersonalEmailTextBox.Text,
    				.BusinessEmail = BusinessEmailTextBox.Text,
    				.Phone = PhoneTextBox.Text
    			}
    
    			Dim validationResult = ValidationHelper.ValidateEntity(contact)
    
    			If Not validationResult.HasError Then
    				_bsContacts.Add(contact)
    				If _dataGridViewSizeDone Then
    					Return
    				End If
    
    				dataGridView1.ExpandColumns()
    				_dataGridViewSizeDone = True
    
    			Else
    				MessageBox.Show(validationResult.ErrorMessageList())
    			End If
    		End Sub
    		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    			dataGridView1.DataSource = _bsContacts
    		End Sub
    	End Class
    End Namespace
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    Wednesday, November 18, 2020 9:29 PM
  • Hi Kareninstructor 

    Thank you for getting back to me. I have a class folder and I named it SQLControl.

    Imports System.Data.SqlClient
    
    Public Class SQLControl
    
        Public ConnectionString As String = ""
        Public ConnectionObj As System.Data.SqlClient.SqlConnection = Nothing
        Public TransactionObj As System.Data.SqlClient.SqlTransaction = Nothing
    
    
        Public SQLCon As New SqlConnection("My Or Your connection string")
        Public SQLCmd As SqlCommand
    
        'DATABASE DATA
        Public SQLDA As SqlDataAdapter
        Public SQLDT As DataTable
        Public SQLDS As DataSet
        Public SQLBS As BindingSource
        Public SQLCB As SqlCommandBuilder
    
        'QUERY PARAMETERS
        Public Params As New List(Of SqlParameter)
    
        'QUERY STATISTICS
        Public RecordCount As Integer
        Public Exception As String
    
        Public Sub ExecQuery(Query As String)
            'rest query stats
            RecordCount = 0
            Exception = ""
    
            Try
                SQLCon.Open()
    
                'CREATE SQL COMMAND
                SQLCmd = New SqlCommand(Query, SQLCon)
    
                'LOAD PARAMETERS INTO SQL COMMAND
                Params.ForEach(Sub(p) SQLCmd.Parameters.Add(p))
    
                'CLEAR PARAMETERS LIST
                Params.Clear()
    
                'EXECUTE COMMAND AND FILL DATASET
                SQLDT = New DataTable
                SQLDA = New SqlDataAdapter(SQLCmd)
    
                RecordCount = SQLDA.Fill(SQLDT)
    
                SQLCon.Close()
    
                'capture ant exceptions
            Catch ex As Exception
                Exception = ex.Message
            Finally
                'check if Connection is open, if still open then Close connection
                If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
            End Try
        End Sub
    
        Public Sub RunQuery(Query As String)
            'RESET QUERY STATISTICS
            RecordCount = 0
            Exception = ""
    
            Try
                SQLCon.Open()
                'create command
                SQLCmd = New SqlCommand(Query, SQLCon)
    
                'FILL DATASET
                SQLDA = New SqlDataAdapter(SQLCmd)
                Params.ForEach(Sub(p) SQLCmd.Parameters.Add(p))
    
                'CLEAR PARAMETERS LIST
                Params.Clear()
    
                'EXECUTE COMMAND & Fill DATASET
                SQLDT = New DataTable
                SQLDA = New SqlDataAdapter(SQLCmd)
    
                RecordCount = SQLDA.Fill(SQLDT)
    
                SQLCon.Close()
            Catch ex As Exception
                'CAPTURE ERROR
                Exception = "ExecQuery Error: " & vbCrLf & ex.Message
            Finally
                'CLOSE CONNECTION
                If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
            End Try
    
        End Sub
    
        Public Sub GetValue(Command As String)
    
            Try
                SQLCon.Open()
                'create command
                SQLCmd = New SqlCommand()
    
    
                SQLCon.Close()
            Catch ex As Exception
                'CAPTURE ERROR
                Exception = "ExecQuery Error: " & vbCrLf & ex.Message
            Finally
                'CLOSE CONNECTION
                If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
            End Try
    
    
    
        End Sub
    
    
        Public Sub RunCheckPassword(CheckPassword As String)
            Try
                SQLCon.Open()
                SQLCmd = New SqlCommand(CheckPassword, SQLCon)
    
                SQLDA = New SqlDataAdapter(SQLCmd)
                SQLDS = New DataSet
                SQLDA.Fill(SQLDS)
                SQLCon.Close()
    
            Catch ex As Exception
                MsgBox(ex.Message)
                If SQLCon.State = ConnectionState.Open Then
                    SQLCon.Close()
    
                End If
            End Try
    
        End Sub
        'For New Empty Sub
        Public Sub New()
    
        End Sub
        'For Adding a new Connection string other than main connection
        Public Sub New(ConnectionString As String)
            SQLCon = New SqlConnection(ConnectionString)
        End Sub
        'Adding New Parameter
        Public Sub AddParam(Name As String, Value As Object)
            Dim NewParam As New SqlParameter(Name, Value)
            Params.Add(NewParam)
        End Sub
        'Check for Connection
        Public Function HasConnection()
            Try
                SQLCon.Open()
    
    
                SQLCon.Close()
                Return True
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            Return False
        End Function
    
        'ERROR CHECKING
        Public Function HasException(Optional Report As Boolean = False) As Boolean
            If String.IsNullOrEmpty(Exception) Then Return False
            If Report = True Then MsgBox(Exception, MsgBoxStyle.Critical, "Exception:")
            Return True
        End Function
    
    
    End Class

    But with what you showed me would the code handle Strings, Numeric (Doubles, Decimals) date and Datetime? also calculations of sums? ...

    Kind regards

    Gary


    Gary Simpson

    Wednesday, November 18, 2020 10:25 PM
  • Hi

    A very brief look at your code.  I seem to see a possible issue with the If .... Else ..... End If blocks. I think there is no proper match for the ElseIf (just below your problem comment) - if I am correct, then try changing the ElseIf to If and see if it will compile.


    Regards Les, Livingston, Scotland


    Hi Les Thank you for getting back to me. I have tried your suggestion. But when the first message box shows and I click yes, I expected to go to the textbox (txtPriceOfJob) So I could insert a price.

    Instead I get the second message box as soon as I click Yes on the first message box.

    Kind Regards

    Gary


    Gary Simpson

    Hi

    OK, here is a try at what *maybe* is required. (I couldn't fully rationalize some of the references in your code)

    	Private Sub CmdCreateInvoice_Click(sender As Object, e As EventArgs) Handles CmdCreateInvoice.Click
    
    		If GetDec((txtPriceOfJob.Text)) = 0D Then
    
    			Dim Message1 As String = "Have you forgotten to enter the Price of the job?"
    			Dim Caption1 As String = LbUsername.Text & ", There is no Price for Job"
    			Dim Buttons1 As MessageBoxButtons = MessageBoxButtons.YesNo
    			Dim Result1 As DialogResult
    
    			Result1 = MessageBox.Show(Message1, Caption1, Buttons1)
    
    			If Result1 = DialogResult.Yes Then
    				' Go to TxtPartPrice1 ????
    				CmdUpdate.PerformClick()
    				txtPriceOfJob.Select()
    				Exit Sub
    			End If
    		End If
    
    		If GetDec(lbTotalPartsPrice.Text) = 0D Then
    			Dim Message As String = "Have you forgotten to enter the Price of Parts?" & vbCrLf &
    								vbCrLf & "Click Yes to Add Price of Parts," &
    								vbCrLf & "Once Prices are Added, 'Click Save Update Button' " &
    								vbCrLf & vbCrLf & "Else" &
    								vbCrLf & vbCrLf & "Click No to Produce an Invoice without Part Prices"
    			Dim Caption As String = LbUsername.Text & ", No Price's have been Added for Parts"
    			Dim Buttons As MessageBoxButtons = MessageBoxButtons.YesNo
    			Dim Result As DialogResult
    
    			Result = MessageBox.Show(Message, Caption, Buttons)
    
    			If Result = DialogResult.Yes Then
    				lbTotalPartsPrice.Select()
    			End If
    		End If
    
    		If GetDec(lbTotalPartsPrice.Text) > 0D AndAlso GetDec((txtPriceOfJob.Text)) > 0D Then
    			UpdateJob2()
    			InsertIntoJobCompleted()
    			PrintDocument1.Print()
    		End If
    
    	End Sub
    	Function GetDec(s As String) As Decimal
    		Dim v As Decimal = 0D
    		If Decimal.TryParse(s, v) Then Return v
    		Return 0D
    	End Function


    Regards Les, Livingston, Scotland

    • Marked as answer by Gary Simpson Wednesday, November 18, 2020 11:41 PM
    Wednesday, November 18, 2020 10:39 PM
  • Les Your Brilliant 

    Thanks again for your help, it really is appreciated I inserted the code I needed into your code.

    It works really well Thank you Les. I was going to try and re-write the whole forms code. In fact I started to create another form and try something different. 

    But hey Les you fixed my issue Thank you very very Much.

    Best Regards to you

    Gary


    Gary Simpson

    Wednesday, November 18, 2020 11:41 PM
  • Even though you have selected a solution and you have asked about mine.

    What mine does for simple example is annotate properties in a class with rules, in this case simple rules but they can get very complex but also still easy to use.

    We have two TextBox controls, one a regular TextBox and the other a NumericTextBox I created.

    Here is the class used to store information from a windows form.

    Public Class Products
        Public Property ProductID As Integer
        <Required(ErrorMessage:="{0} Required")>
        <StringLength(30, MinimumLength:=3, ErrorMessage:="Invalid {0}")>
        Public Property ProductName As String
        <Required(ErrorMessage:="{0} Required")>
        <Range(1, Decimal.MaxValue, ErrorMessage:="Please enter a value bigger than {1} for {0}")>
        Public Property UnitPrice As Decimal
    End Class

    We validate by creating a new instance of Products and pass the class to the validator. The Validate checks property values against annotations as per the first code block. If there is no problem the class instance can be used in a data class (I never write what can be written in a class in a form) to add, edit data in a database.

    Public Class Form1
        Private Sub ValidateButton_Click(sender As Object, e As EventArgs) _
            Handles ValidateButton.Click
    
            Dim product As New Products With {
                    .ProductName = ProductNameTextBox.Text,
                    .UnitPrice = UnitPriceTextBox.AsDecimal}
    
            Dim validationResult As EntityValidationResult = ValidationHelper.ValidateEntity(product)
            If validationResult.HasError Then
                MessageBox.Show(validationResult.ErrorMessageList())
            End If
    
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    • Marked as answer by Gary Simpson Friday, November 20, 2020 6:30 PM
    Thursday, November 19, 2020 1:17 AM