Frage

Good afternoon,

I would like some help with the code for validating the text that is being entered into an inputbox in vb / winforms.

Current Code:

stringFromInputBox = InputBox("How much has the customer paid? " + Environment.NewLine + Environment.NewLine + "Don't forget to amend the account or take the cash through EPOS." + Environment.NewLine + Environment.NewLine + "Balance Due : £" + balanceDue.ToString + " ", "PAYMENT TAKEN")

I would like to be able to stop the user from entering anything other than numbers, but also allow them to enter a decimal (for £5.50 for example). I would also like to restrict the minimum to 0, and the maximum to be balanceDue.

I have found several, rather long winded ways to do this, but I am hoping that the .net framework has some more efficient and less 'brittle' methods.

War es hilfreich?

Lösung

Your best option is to create a new Form with all the features, inputs and things you need and show it with .ShowDialog() to be modal like the InputBox.

Andere Tipps

Since InputBox is only a function you can create your own something like this:

Private Function InputBox(Title As String, Prompt As String, Validate As Boolean) As String
    Dim Result As String = Microsoft.VisualBasic.Interaction.InputBox(Prompt, Title)
    'If the cancel button wasn't pressed and the validate flag set to true validate result
    If Not Result = "" AndAlso Validate Then
        'If it's not a number get new input.  More conditions can easily be added here
        'declare a double and replace vbNull with it, to check for min and max input.
        If Not Double.TryParse(Result, vbNull) Then
            MsgBox("Invalidate Input")
            Result = InputBox(Title, Prompt, True)
        End If
    End If
    Return Result
End Function

Then call it like this: InputBox("Data Entry", "Numbers only please", True)

I didn't implement any of the other options, but that can easily be added.

You could use a regex on the validating event of the inputbox control:

Private Sub InputBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles InputBox.Validating
    'Uses tryparse to alter the value to an integer, strips out non digit characters (removed £ and other currency symbols if required) - if it fails default to zero
    Dim num As Integer
    If Integer.TryParse(Regex.Replace(InputBox.Text, "[^\d]", ""), num) = False Then
        num = 0
    End If
    _Controller.CurrentRecord.InputBox = num
End Sub
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top