Do you know how to restrict user input in textbox, this textbox only accepts integer? By the way I'm developing for Windows 8. I've tried what I searched from SO and from Google but it's not working,
Asked
Active
Viewed 3.0k times
6
-
Have you looked at the char.IsNumeric method..? checking this on the Key Press, or Key Down Events..? – MethodMan Feb 11 '13 at 14:26
-
yup i have a warning message keychar is not found – Dunkey Feb 11 '13 at 15:07
-
better show some code .. because there are KeyEvents that you can use to get that... if not perhaps you need to setup a Mask on that field – MethodMan Feb 11 '13 at 15:40
4 Answers
11
If you don't want to download the WPF ToolKit (which has both the IntegerUpDown control or a MaskedTextBox), you can implement it yourself as adapted from this article on Masked TextBox In WPF using the UIElement.PreviewTextInput
and DataObject.Pasting
events.
Here's what you would put in your window:
<Window x:Class="WpfApp1.MainWindow" Title="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Vertical" Width="100" Height="100" HorizontalAlignment="Left" VerticalAlignment="Top">
<TextBlock Name="NumericLabel1" Text="Enter Value:" />
<TextBox Name="NumericInput1"
PreviewTextInput="MaskNumericInput"
DataObject.Pasting="MaskNumericPaste" />
</StackPanel>
</Window>
And then implement the C# in your codebehind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MaskNumericInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !TextIsNumeric(e.Text);
}
private void MaskNumericPaste(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
string input = (string)e.DataObject.GetData(typeof(string));
if (!TextIsNumeric(input)) e.CancelCommand();
}
else
{
e.CancelCommand();
}
}
private bool TextIsNumeric(string input)
{
return input.All(c => Char.IsDigit(c) || Char.IsControl(c));
}
}

KyleMit
- 30,350
- 66
- 462
- 664
6
public class IntegerTextBox : TextBox
{
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
Text = new String(Text.Where(c => Char.IsDigit(c)).ToArray());
this.SelectionStart = Text.Length;
}
}

Nathan Hillyer
- 1,959
- 1
- 18
- 22
1
At the most raw level you can intercept the KeyUp
event or TextChanged
to see what char is being added and remove it if it cannot be parsed to Int.
Also check - Only accept digits for textbox and Masking Textbox to accept only decimals
0
You could use a integer up down control. There's one in the WPF toolkit that will do the trick:
https://wpftoolkit.codeplex.com/wikipage?title=IntegerUpDown

GrandMasterFlush
- 6,269
- 19
- 81
- 104