Reputation: 3751
I have a textbox in my windows form application and I am trying to use the following condition to see if they match:
Can only enter A-F(a-f) and 0-9
Backspace/Delete/Arrow keys are allowed
I have the following code-behind (default text is FFFFFF
on form load):
private void tbHex_TextChanged(object sender, EventArgs e)
{
Regex rx = new Regex(@"^[a-fA-F0-9");
MatchCollection mc = rx.Matches(tbHex.Text);
if (mc.Count > 0) //if anything other than what is asked is entered...
{
MessageBox.Show("NO!");
}
}
What is happening when the form load is, I am displayed with the "NO!" message box.
How can I modify so the user can ONLY enter the valid characters/keys and also does the same validation when pasting into the textbox as well as entering it character by character.
Upvotes: 0
Views: 113
Reputation: 11035
Text changed happens at form load when the text is originally set. It will also fire at every character keystroke. You could use an event such as Validating
or Validated
if you only want it to only fire after user changes the text.
Upvotes: 1