【问题标题】:how do i restrict numericupdown control to accept only integers我如何限制 numericupdown 控件只接受整数
【发布时间】:2011-08-24 16:45:09
【问题描述】:

我有一个 windows numericupdown 控件。我想限制它,以便用户只能在其中输入整数。我怎么做?目前,用户也可以输入十进制数。 谢谢 PS我正在使用.net

【问题讨论】:

    标签: .net integer numericupdown


    【解决方案1】:

    我做了一些实验,发现了这个解决方法:

        private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar < 48 || e.KeyChar > 57)
            {
                e.Handled = true;
            }
        }
    

    这样你也不能输入千位分隔符,但你可以通过首先找出千位分隔符并允许它来添加它。

    【讨论】:

    • 您可能希望允许退格 - 检查上面的 (e.KeyChar != 8)。
    • @amolbk - yes 和其他键(箭头、home、end、Ctrl-C、V 和 X)也可能有用。
    • 复制粘贴可能仍有问题
    • 很容易接受Copy。在粘贴之前,可能需要检查剪贴板是否包含可以/应该显示的有效数据
    【解决方案2】:

    DecimalPlaces 属性设置为零。

    【讨论】:

      【解决方案3】:

      如果您使用的是 AjaxControlToolkit,您可以将 FilteredTextBoxExtender 与 NumericUpDownExtender 结合使用:

      <asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender" runat="server" TargetControlID="TextBoxNums" FilterType="Numbers">
      </asp:FilteredTextBoxExtender>
      <asp:NumericUpDownExtender ID="NumericUpDownExtender" runat="server" TargetControlID="TextBoxNums" Width="10">
      </asp:NumericUpDownExtender>
      <asp:TextBox ID="TextBoxNums" runat="server"></asp:TextBox>
      

      【讨论】:

      • 糟糕,我刚刚注意到您使用的是 Windows 窗体而不是 Web 窗体
      【解决方案4】:

      如果您有权访问DevExpress 控件,则应使用SpinEdit 控件并将其Properties.IsFloatValue 设置为false

      【讨论】:

        【解决方案5】:

        我使用它来不允许在当前系统上输入数字小数分隔符:

        private void NumericUpDown_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Do not accept the default decimal separator
            char sep = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
            if (e.KeyChar == sep)
            {
                e.Handled = true;
            }
        }
        

        一切正常(退格等)

        【讨论】:

          【解决方案6】:

          设置DecimalPlaces = 0:

          public class IntegerUpDown : NumericUpDown
             {
                public IntegerUpDown(): base() 
                {
                   DecimalPlaces = 0;
                }
          
                protected override void OnTextBoxTextChanged(object source, EventArgs e) 
                {
                   base.OnTextBoxTextChanged( source, e);
                   ValidateEditText();
                }
             }
          

          请参阅文档:https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.numericupdown.decimalplaces

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-06
            相关资源
            最近更新 更多