【问题标题】:Masking to accept positive decimals屏蔽以接受正小数
【发布时间】:2013-01-30 11:12:24
【问题描述】:

我有一个textBox,我希望它只接受0.0020.00 之间的正小数,我该怎么做?

【问题讨论】:

  • 请发布一些代码,以便我们为您提供帮助

标签: vb.net winforms textbox


【解决方案1】:

如果您需要确保在用户键入时只输入小数,则使用 javascript 对其应用一个 on key up 事件,该事件会检查文本框的内容,如果存在则删除任何违规字符。

如果您只需要检查提交,请在表单提交时调用的代码中进行。

【讨论】:

  • 对不起,我用的是winform
【解决方案2】:

您可以像这样在TextBox 上使用验证器

<asp:RangeValidator ID="range" runat="server" 
    ControlToValidate="text1" 
    MinimumValue="0" MaximumValue="20.99" Type="double" />

请查看这篇关于compareValidatorrangeValidatorregularExpressionValidator的文章了解更多详情

祝你好运

【讨论】:

  • 对不起,我用的是winform
【解决方案3】:

如果我理解你的问题。

   Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c Then
            e.Handled = True
        End If

        'for ne decimal point
        If (e.KeyChar = "."c AndAlso (TextBox1).Text.IndexOf("."c) > -1) Then
            e.Handled = True
        End If
    End Sub

    Private Sub TextBox1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
        If Decimal.Parse(TextBox1.Text) >= 0 AndAlso Decimal.Parse(TextBox1.Text) <= 20 Then
            'if positive decimals between 0.00 and 20.00
            'Do stuff
        Else
            'if not positive decimals between 0.00 and 20.00
            e.Cancel = True
        End If
    End Sub

【讨论】:

  • 我试过这段代码,但是当我写一些像 10.00 这样的值时,当我写一些没有 .像 11 它不会让我专注于其他控件此错误消息:Input string was not in a correct format.
  • 等等..这只是数字之间的一个例子,我会修改我的答案
  • 您使用的是什么版本的 .Net 框架?我已经修改了答案
  • 我的代码在 .Net 4 中测试。我将在 .net 3.5 中尝试,请稍等。
  • 我在 3.5 中测试,一切都很好。请检查您在什么情况下复制粘贴代码?
【解决方案4】:
    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles TextBox1.TextChanged

    Dim myRegex As New Regex("^[0-9]*\.?[0-9]{0,2}$")
    If myRegex.IsMatch(TextBox1.Text.Trim) = False Then
        MsgBox("Invalid characters found")
        Exit Sub
    Else
        If CDec(TextBox1.Text.Trim) < 0 OrElse CDec(TextBox1.Text.Trim) > 20 Then
            MsgBox("Enter value between 0.00 and 20.00")
            Exit Sub
        End If
    End If

    End Sub

【讨论】:

  • 您的正则表达式将接受例如 100。这就是为什么在进行任何比较之前最好将字符串转换为数字
  • @Necto:是的,正则表达式将接受 100,但第二个 if 条件将处理这个问题。正则表达式是为了避免减号(例如:-10.00)
猜你喜欢
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多