0

下午好,

我想要一些关于验证正在输入到 vb / winforms 中的输入框中的文本的代码的帮助。

当前代码:

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")

我希望能够阻止用户输入除数字以外的任何内容,但也允许他们输入小数(例如 5.50 英镑)。我还想将最小值限制为 0,并将最大值限制为 balanceDue。

我已经找到了几种相当冗长的方法来做到这一点,但我希望 .net 框架有一些更有效且不那么“脆弱”的方法。

4

3 回答 3

1

您最好的选择是创建一个包含所有功能、输入和您需要的东西的新表单,并将其显示.ShowDialog()为像 InputBox 一样的模态。

于 2013-06-14T12:20:38.753 回答
0

由于 InputBox 只是一个函数,因此您可以创建自己的函数,如下所示:

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

然后像这样调用它:InputBox("Data Entry", "Numbers only please", True)

我没有实现任何其他选项,但可以轻松添加。

于 2013-06-14T18:48:45.380 回答
0

您可以在输入框控件的验证事件上使用正则表达式:

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
于 2013-06-16T09:44:52.447 回答