1

I'm writing some code to sanitise input. For examples sake, let's use the following (note that I know to use PreviewInput for numerics, this is just for examples sake):

static bool IsDigitsOnly(string str)
{
    return str.All(c => (c >= '0' && c <= '9') || c == '.');
}

private void KeyUpTextBoxNumberCheck(object sender, KeyEventArgs e)
{
    if (!IsDigitsOnly(TextBoxExternalReferralOther1.Text))
    {
        TextBoxExternalReferralOther1.Text = "";
    }
}

I'm trying to update KeyUpTextBoxNumberCheck so it can work with multiple textboxes. How can I update it so that the textboxes aren't hardcoded and instead come from the sender?

Michael A
  • 9,480
  • 22
  • 70
  • 114
  • Try to use [AllowableCharactersTextBoxBehavior](http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf) this will be more easy for reuse, just attach behavior to textbox you need and supply it with regex and max characters count. – Shakra Jan 17 '17 at 06:08
  • Can't edit last comment due to 5 mins :(( If `KeyUpTextBoxNumberCheck` binded to you textbox event, then `sender` is textbox you are looking for. You could use it as `!IsDigitsOnly((sender as TextBox).Text)` – Shakra Jan 17 '17 at 06:15
  • @Shakra Oh that's fantastic! Thought it might be a simple fix but was coming up short on Google. Would you mind posting as an answer so I can accept for future visitors? – Michael A Jan 17 '17 at 06:24

1 Answers1

2

Try to use AllowableCharactersTextBoxBehavior this will be more easy for reuse, just attach behavior to TextBox you need and supply it with regex and max characters count.

If you want to use shown code and KeyUpTextBoxNumberCheck is binded to TextBox event, you cant change it to :

private void KeyUpTextBoxNumberCheck(object sender, KeyEventArgs e)
{
    if (!IsDigitsOnly((sender as TextBox).Text))
    {
        (sender as TextBox).Text = "";
    }
}
Community
  • 1
  • 1
Shakra
  • 501
  • 2
  • 8