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
Asked
Active
Viewed 1.0k times
6 Answers
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
-
3You might want to allow backspace - check for (e.KeyChar != 8) above. – amolbk Mar 01 '13 at 10:24
-
@amolbk - yes and other keys (arrows, home, end, Ctrl-C,V and X) might be usefull too. – Emond Mar 01 '13 at 11:28
-
Copy and paste may still be problematic – Christoph Nov 17 '14 at 16:49
-
It is easy to accept Copy. Before pasting it might be needed to check whether or not the clipboard contains valid data that can/should be displlayed – Emond Aug 16 '17 at 12:31
-
1Is not a bad answer but at the present day is better use DecimalPlaces = 0 – Leandro Bardelli Mar 25 '23 at 15:46
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

user3894842
- 11
- 1
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