6

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,

iltzortz
  • 2,342
  • 2
  • 19
  • 35
Dunkey
  • 1,900
  • 11
  • 42
  • 72

4 Answers4

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

Community
  • 1
  • 1
dutzu
  • 3,883
  • 13
  • 19
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