【问题标题】:Winforms TextBox - Allow numeric or 1 decimal place onlyWinforms TextBox - 仅允许数字或 1 个小数位
【发布时间】:2011-11-21 18:45:04
【问题描述】:

如何防止用户输入除数值有 1 个小数位的十进制值以外的任何内容?

应该允许用户输入任意长度的字符(如果是十进制值,则在小数点之前)。

【问题讨论】:

    标签: winforms textbox


    【解决方案1】:

    尝试使用Regex。这种模式应该可以工作:Regex match = new Regex(@"^[1-9]\d*(\.\d{1})?$"),把它放在文本框的验证事件中。如果不匹配,Undo() 或删除 Textbox.Text 属性。

        Regex match = new Regex(@"^[1-9]\d*(\.\d{1})?$");
    
        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            if (!match.IsMatch(textBox1.Text))
            {
                textBox1.Undo(); 
            }
        }
    

    要真正立即撤消输入,您必须使用

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (!match.IsMatch(textBox1.Text))
            {
                textBox1.Undo();
            }
        }
    

    因为如果你使用 KeyDown,TextBox 就没有 Undo State。

    第二次编辑:如果您希望两种情况都匹配,则必须在验证事件或类似事件中进行检查。由于正则表达式使用“$”来确保最后没有添加任何字符,因此您无法输入“。”否则你最终会得到一个像 1 这样的数字,这需要额外的检查。

    【讨论】:

      【解决方案2】:

      这一次聚会可能有点晚了,但我扩展了一个简单的文本框以强制输入始终为十进制格式。简单但有效

      Imports System.Runtime.InteropServices
      Imports System.Drawing.Imaging
      Imports System.ComponentModel
      Imports System.Text.RegularExpressions
      
      
      <ToolboxBitmap(GetType(System.Windows.Forms.TextBox))> _
      Public Class NumericTextBox
          Inherits TextBox
      
          Dim _TextBoxValue As String
          Dim _CaretPosition As Integer
      
          Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
              MyBase.OnKeyDown(e)
              _TextBoxValue = Me.Text
              _CaretPosition = Me.SelectionStart
          End Sub
          Protected Overrides Sub OnKeyUp(e As KeyEventArgs)
              MyBase.OnKeyUp(e)
      
              If (Me.Text.Length = 0) Or (Me.Text = _TextBoxValue) Then Exit Sub
              If IsNumeric(Me.Text) Then
      
                  If Me.Text.EndsWith(".") Then
                      Me.Text = Convert.ToDecimal(Me.Text) & "."
                  Else
                      Me.Text = Convert.ToDecimal(Me.Text)
                  End If
      
              Else
                  Me.Text = _TextBoxValue
              End If
              Me.SelectionStart = _CaretPosition + 1
          End Sub
      End Class
      

      【讨论】:

        【解决方案3】:

        正则表达式匹配 = 新正则表达式(@"^[1-9]\d*(.\d{1})?$"); 正常工作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多