9

I have a windows numericupdown control. I want to restrict it so that user can only enter integers in it. How do I do that? At present a user can enter a decimal number as well. Thanks PS I am using .net

skaffman
  • 398,947
  • 96
  • 818
  • 769
umbersar
  • 1,821
  • 3
  • 24
  • 34

6 Answers6

9

Set the DecimalPlaces property to zero.

Jamie Kitson
  • 3,973
  • 4
  • 37
  • 50
9

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.

Emond
  • 50,210
  • 11
  • 84
  • 115
1

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

Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42
0

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>
msnorth
  • 305
  • 2
  • 14
0

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

Szabolcs Antal
  • 877
  • 4
  • 15
  • 27
0

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.)

TechAurelian
  • 5,561
  • 5
  • 50
  • 65