在VB / net中验证winform输入框文本

时间:2013-06-14 12:07:53

标签: vb.net winforms inputbox

下午好,

我想帮助验证在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框架有一些更有效,更少“脆弱”的方法。

3 个答案:

答案 0 :(得分:1)

您最好的选择是创建一个包含所有功能,输入和所需内容的新表单,并使用.ShowDialog()将其显示为与InputBox类似的模态。

答案 1 :(得分: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)

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

答案 2 :(得分: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