【问题标题】:Validation winform inputbox text in VB/netVB/net中验证winform输入框文本
【发布时间】:2013-06-14 12:07:52
【问题描述】:

下午好,

我想要一些关于验证正在输入到 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 框架有一些更有效且不那么“脆弱”的方法。

【问题讨论】:

  • 默认的InputBox 不提供此功能。您必须自己创建一个窗口(输入框)并添加所需的验证。
  • 最好的办法是创建一个表单并提供这些功能。输入框不允许你做这些事情。
  • @DazEvans :为什么不使用带有按键事件的文本框而不是输入框?

标签: vb.net winforms inputbox


【解决方案1】:

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

【讨论】:

  • 感谢 SysDragon。我希望我不必那样做……该死。
【解决方案2】:

由于 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)

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

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多