Textbox PreviewTextInput - accept only numbers and ':'

c#, textbox, wpf

Solution

Just use boolean logic:

foreach (var ch in e.Text)
{
    if (!(Char.IsDigit(ch) || ch.Equals(':')))
    {
        e.Handled = true;
        break;
    }
}

Problem

I have this code: ``` foreach (char ch in e.Text) { if (!Char.IsDigit(ch)) e.Handled = true; else { if(!(ch.Equals(':'))) e.Handled = true; } } ``` when there is only ``` if (!Char.IsDigit(ch)) e.Handled = true; ``` I can write numbers and when I use only the second if(), I can write only ' : '. But when I use both of them I can't write anything.

Original source