Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Numeric Input Validation

$
0
0

The idea is to validate numeric user input into a textbox.  If the user enters a letter, that last input (the letter) should be deleted.

The following is the textbox definition in the xaml file.

            <TextBox x:Name="numericTextBox1"  KeyDown="numericTextBox1_KeyDown"/>

The issue is that it produces unexpected results.  For instance, if the user enters:  1234r

the textbox displays r123 instead of 1234.  What am I missing?

The following is the code in the cs file.  

 

 private void numericTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        checkKey(numericTextBox1, e);
    }

                    

    private void checkKey(TextBox textBox, KeyEventArgs e)
    {
        if (e.Key != Key.D0 &&
            e.Key != Key.D1 &&
            e.Key != Key.D2 &&
            e.Key != Key.D3 &&
            e.Key != Key.D4 &&
            e.Key != Key.D5 &&
            e.Key != Key.D6 &&
            e.Key != Key.D7 &&
            e.Key != Key.D8 &&
            e.Key != Key.D9 &&
            e.Key != Key.NumPad0 &&
            e.Key != Key.NumPad1 &&
            e.Key != Key.NumPad2 &&
            e.Key != Key.NumPad3 &&
            e.Key != Key.NumPad4 &&
            e.Key != Key.NumPad5 &&
            e.Key != Key.NumPad6 &&
            e.Key != Key.NumPad7 &&
            e.Key != Key.NumPad8 &&
            e.Key != Key.NumPad9 &&
            e.Key != Key.OemPeriod &&
            e.Key != Key.Decimal)
        {

           string text;
           text = text.Substring(0, text.Length - 1);
           MessageBox.Show("text string after removing last place:  " + text);
           textBox.Text = text;

        }
    }


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>