简体   繁体   中英

How to force textbox to take only numbers in WPF?

I want user to enter only numeric values in TextBox .

I got this code:

private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
     int isNumber = 0;
     e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}

But I am not getting textbox_KeyPress event and e.KeyChar while using WPF.

Whats the solution in WPF?

Edit:

I made a Solution!

private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    CheckIsNumeric(e);
}

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;

    if(!(int.TryParse(e.Text, out result) || e.Text == "."))
    {
        e.Handled = true;
    }
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        char c = Convert.ToChar(e.Text);
        if (Char.IsNumber(c))
            e.Handled = false;
        else
            e.Handled = true;

        base.OnPreviewTextInput(e);
    }

You can use a validation rule... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

Or make your own Maskable textbox http://rubenhak.com/?p=8

You can bind your textbox with a dependency property and inside dependency property's validation method you can check if int.tryparse returns true then fine otherwise you can go for default or you can reset value.

Or you can use WPF ValidationRules to find out when the value is changed. Once changed you can apply logic for inout validaiton.

Or you can use IDataError Info for validation.

In WPF the keycode values are different from the normal winforms e.keychar values,

In the PreviewKeyDown event of the textbox, add this code:

if ((e.key < 34) | (e.key > 43)) {
if ((e.key < 74) | (e.key > 83)) {
    if ((e.key == 2)) {
        return;
        }
    e.handled = true;
    }
}

This will allow the User to only enter Numbers in the Numpad0 - Numpad9 section and the D0 - D9 and also the key.Back

Hope this Helps, cheers!

bit enhanced version of Hasib Uz Zaman

     private void txtExpecedProfit_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric((TextBox)sender,e);
    }

    private void CheckIsNumeric(TextBox sender,TextCompositionEventArgs e)
    {
        decimal result;
        bool dot = sender.Text.IndexOf(".") < 0 && e.Text.Equals(".") && sender.Text.Length>0;
        if (!(Decimal.TryParse(e.Text, out result ) || dot )  )
        {
            e.Handled = true;
        }
    }

this will check for duplication .(decimal mark) and will not allow just only .(decimal mark)

//Call this code on KeyDown Event
if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key == Key.Back))
{ e.Handled = false; }
else if((e.Key >= Key.D0 && e.Key <= Key.D9))
{ e.Handled = false; }
else
{ e.Handled = true; }
private void shomaretextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // xaml.cs code
  if (!char.IsDigit(e.Text, e.Text.Length - 1))
    e.Handled = true;
}

In xaml

<TextBox x:Name="shomaretextBox" 
         HorizontalAlignment="Left" 
         Height="28" 
         Margin="125,10,0,0" 
         TextWrapping="Wrap" 
         VerticalAlignment="Top" 
         Width="151" 
         Grid.Column="1"        
         TextCompositionManager.PreviewTextInput="shomaretextBox_PreviewTextInput" />

我相信你正在寻找的是PreviewTextInput事件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM