Datsheep
Datsheep

Reputation: 549

Textbox PreviewTextInput - accept only numbers and ':'

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.

Upvotes: 2

Views: 11839

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186728

Just use boolean logic:

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

Upvotes: 5

Liam Morrow
Liam Morrow

Reputation: 56

Another way to do this would be using a linq statement. It comes down to personal preference but many find linq to be more readable.

e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));

It's a fairly easy one liner and with the coming of c# 6 the entire method could be written as a lambda function like so:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) =>
    e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));

Keep in mind that PreviewTextInput does not handle space characters and these methods will not filter them out. An explanation is provided on the MSDN forums

Because some IMEs will treat whitespace keystroke as part of the text composition process, that's why it eats up by Avalon to report correct composited text through TextInput event.

Upvotes: 2

Related Questions