Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force textbox to take only numbers in WPF?

Tags:

c#

.net

wpf

textbox

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;
    }
}
like image 454
Hasib Uz Zaman Avatar asked Sep 08 '25 14:09

Hasib Uz Zaman


1 Answers

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);
    }
like image 110
Niki Nikpour Avatar answered Sep 10 '25 11:09

Niki Nikpour