开发者

how do i restrict numericupdown control to accept only integers

I have a windows numericupdown control. I want to restrict it so that user can only enter integer开发者_运维问答s in it. How do I do that? At present a user can enter a decimal number as well. Thanks PS I am using .net


I did a little experimenting and found this workaround:

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

This way you will not be able to type thousand separators either but you could add that by first finding out what the thousand separator is and allowing that too.


Set the DecimalPlaces property to zero.


Set DecimalPlaces = 0:

public class IntegerUpDown : NumericUpDown
   {
      public IntegerUpDown(): base() 
      {
         DecimalPlaces = 0;
      }

      protected override void OnTextBoxTextChanged(object source, EventArgs e) 
      {
         base.OnTextBoxTextChanged( source, e);
         ValidateEditText();
      }
   }

See docs: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.numericupdown.decimalplaces


If you are using the AjaxControlToolkit, you can just combine the FilteredTextBoxExtender with the 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>


If you have access to DevExpress controls, you should use a SpinEdit control and set its Properties.IsFloatValue to false.


I'm using this to not allow the typing of the number decimal separator on the current system:

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;
    }
}

Everything else works (Backspace, etc.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜