在写入文件之前验证子过程

时间:2016-02-19 00:13:03

标签: vb.net

我的程序数据验证存在问题。如果用户输入不正确的数据,它会正确显示带有错误的MessageBox。但是,当您关闭MessageBox而不是清除并将焦点设置在有问题的TextBox上时,它将继续运行其余的子过程。虽然写入文本文件的数据将在错误输入的数据点停止。

现在我知道我错过了很可能非常简单的事情,但我正在上课学习。不幸的是,这本书含糊不清,我在谷歌搜索上找不到任何东西。可能是因为没有问正确的问题。所以对我所缺少的任何指导。

此作业的目的是学习使用类。我的代码基于本书关于主题和作业参数的一个例子。还欢迎任何其他意见或建议。

(category|publisher|subject):(.*?)(?:,(?R)|.?)

我输入一个布尔变量,将一个true或false返回到GetData子。

Public Class Motors
    'Variables for Class
    Public strMotorID As String
    Public strDescription As String
    Public dblRPM As Double
    Public dblVoltage As Double
    Public strStatus As String

    'Constructor
    Public Sub New()
        Debug.WriteLine("Motor object being created.")
        strMotorID = String.Empty
        strDescription = String.Empty
        dblRPM = 0.0
        dblVoltage = 0.0
        strStatus = String.Empty
    End Sub

    'Motor ID property procedure
    Public Property MotorId() As String
        Get
            Return strMotorID
        End Get
        Set(ByVal value As String)
            strMotorID = value
        End Set
    End Property

    'Description property procedure
    Public Property Description() As String
        Get
            Return strDescription
        End Get
        Set(ByVal value As String)
            strDescription = value
        End Set
    End Property

    'RPM property procedure
    Public Property RPM() As Double
        Get
            Return dblRPM
        End Get
        Set(ByVal value As Double)
            dblRPM = value
        End Set
    End Property

    'Voltage property procedure
    Public Property Voltage() As Double
        Get
            Return dblVoltage
        End Get
        Set(ByVal value As Double)
            dblVoltage = value
        End Set
    End Property

    'Status property procedure
    Public Property Status() As String
        Get
            Return strStatus
        End Get
        Set(ByVal value As String)
            strStatus = value
        End Set
    End Property
End Class

Public Class Form1
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close() 'Close the form
    End Sub

    Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
        Dim frmNewMotor As New NewMotorForm 'Declare new form for input
        frmNewMotor.ShowDialog() 'Call new form.
    End Sub
End Class

Public Class NewMotorForm
    Private Sub GetData(ByVal objMotor As Motors)'Sub to get data from user.
        Try
            'Validate motor id is 5 characters long.
            If Len(txtMotorID.Text) > 5 Then
                MessageBox.Show("Check Motor ID input.")

            ElseIf Len(txtMotorID.Text) < 5 Then
                MessageBox.Show("Check Motor ID input.")

            Else
                objMotor.MotorId = txtMotorID.Text 'Correctly passes to Class.
                objMotor.Description = txtDescription.Text 'Correctly passes to Class.

                If Double.TryParse(txtRPM.Text, objMotor.RPM) And CDbl(txtRPM.Text) >= 10 And CDbl(txtRPM.Text) <= 10000 Then
                    objMotor.RPM = CDbl(txtRPM.Text) 'Validate input is within appropriate range. Correctly passes to Class.

                Else
                    'Error message for invalid input
                    MessageBox.Show("Check RPM input.")
                    txtRPM.Clear()
                    txtRPM.Focus()

                End If

                If Double.TryParse(txtVoltage.Text, objMotor.Voltage) And CDbl(txtVoltage.Text) >= 1 And CDbl(txtVoltage.Text) <= 500 Then
                    objMotor.Voltage = CDbl(txtVoltage.Text) 'Validate input is within appropriate range.

                Else
                    'Error message for invalid input.
                    MessageBox.Show("Check Voltage input.")
                    txtVoltage.Clear()
                    txtVoltage.Focus()

                End If
                'Get selection from combobox
                If cmbStatus.SelectedItem.ToString = "ON" Then
                    objMotor.strStatus = "ON"
                ElseIf cmbStatus.SelectedItem.ToString = "OFF" Then
                    objMotor.strStatus = "OFF"
                ElseIf cmbStatus.SelectedItem.ToString = "MNT" Then
                    objMotor.strStatus = "MNT"
                ElseIf cmbStatus.SelectedItem.ToString = "NA" Then
                    objMotor.strStatus = "NA"
                Else
                    MessageBox.Show("Please check Status input.")
                End If   

            End If

        Catch ex As Exception
            MessageBox.Show("Check data input.")
            txtMotorID.Focus()

        End Try
    End Sub

    Private Sub SaveRecord(ByVal objMotor As Motors)
        Dim writer As StreamWriter 'Variable for StreamWriter
        Try
            writer = File.AppendText("Motors.txt") 'Open file to be written
            'Write data from variables to text document.
            writer.WriteLine(objMotor.strMotorID)
            writer.WriteLine(objMotor.strDescription)
            writer.WriteLine(objMotor.dblRPM)
            writer.WriteLine(objMotor.dblVoltage)
            writer.WriteLine(objMotor.strStatus)

            writer.Close() 'close document
        Catch ex As Exception
            MessageBox.Show("Failed to save motor record.")
        End Try
    End Sub

    Private Sub ClearForm()
        'Sub routine to clear the form after user saves file.
        txtMotorID.Clear()
        txtDescription.Clear()
        txtRPM.Clear()
        txtVoltage.Clear()
        cmbStatus.ResetText() 
        txtMotorID.Focus()
    End Sub


    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Me.Close() 'Close Form
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Dim objMotor As New Motors
        GetData(objMotor) 'Get data from Class
        SaveRecord(objMotor) 'Write data to document
        MessageBox.Show("Motor record saved.") 'Message to for completion.
        ClearForm() 'Clear form
    End Sub

    Private Sub NewMotorForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Debug.Listeners.Add(New ConsoleTraceListener())
    End Sub
End Class

然后在btnSave_Click事件中使用和If ... Then语句:

If Len(txtMotorID.Text) > 5 And Len(txtMotorID.Text) < 5 Then
            MessageBox.Show("Check Motor ID input.")
            dataInput = False

            Else
                objMotor.MotorId = txtMotorID.Text 'Correctly passes to Class.
                objMotor.Description = txtDescription.Text 'Correctly passes to Class.

                If Double.TryParse(txtRPM.Text, objMotor.RPM) And CDbl(txtRPM.Text) >= 10 And CDbl(txtRPM.Text) <= 10000 Then
                    objMotor.RPM = CDbl(txtRPM.Text) 'Validate input is within appropriate range. Correctly passes to Class.
            Else

                'Error message for invalid input
                MessageBox.Show("Check RPM input.")
                txtRPM.Clear()
                txtRPM.Focus()
                dataInput = False

                End If

                If Double.TryParse(txtVoltage.Text, objMotor.Voltage) And CDbl(txtVoltage.Text) >= 1 And CDbl(txtVoltage.Text) <= 500 Then
                    objMotor.Voltage = CDbl(txtVoltage.Text) 'Validate input is within approriate range. Does not pass data to Class.
                Else
                    'Error message for invalid input. 
                MessageBox.Show("Check Voltage input.")
                txtVoltage.Clear()
                txtVoltage.Focus()
                dataInput = False
                End If
                'Get selection from combobox
                If cmbStatus.SelectedItem.ToString = "ON" Then
                    objMotor.strStatus = "ON"
                ElseIf cmbStatus.SelectedItem.ToString = "OFF" Then
                    objMotor.strStatus = "OFF"
                ElseIf cmbStatus.SelectedItem.ToString = "MNT" Then
                    objMotor.strStatus = "MNT"
                ElseIf cmbStatus.SelectedItem.ToString = "NA" Then
                    objMotor.strStatus = "NA"
                Else
                MessageBox.Show("Please check Status input.")
                dataInput = False
                End If
            dataInput = True
        End If

但是现在,程序完全忽略了我在用户输入无效数据时设置的所有MessageBoxes,TextBox.Clear和TextBox.Focus。

1 个答案:

答案 0 :(得分:0)

以下是您可以尝试的建议。

使用功能代替Sub

Private Function GetData(ByVal objMotor As Motors) As Boolean
        If Len(txtMotorID.Text) <> 5 Then 'if MotorID length != 5 then take action for wrong input
            MessageBox.Show("Check Motor ID input.")
            txtMotorID.Clear() ' Clear the input
            txtMotorID.Focus() ' Focus to relevent textbox
            Return False 'return false
        End If
        'Use same logic to validate your other inputs
        'don't forget to return true if everything is fine

检查函数的返回值以查看是否可以保存

If GetData(objMotor) Then 'If the data got is validated
    SaveRecord(objMotor) 'Write data to document
    MessageBox.Show("Motor record saved.") 'Message to for completion.
    ClearForm() 'Clear form
End If