One of the problems, at least, is related to what (and how) you are trying to do (for example, Brian indicated so well), you probably mean what allows the first 3 characters of the text field to be in the format "1.3" , for example, and removing char if it is not correct in this position. If you really intended to do this, you can do it (I did not post any code for the case if the user places another character after success, in this case the fourth char):
string isNumber = @"^[1-9]{1}\.[1-9]{1}$"; private void textBox1_TextChanged(object sender, EventArgs e) { TextBox text = (TextBox)sender; Match match; switch (text.Text.Length) { case 1: if (char.IsDigit(text.Text[0])) break; else text.Text = ""; break; case 2: if (char.IsPunctuation(text.Text[1])) break; else { text.Text = text.Text.Remove(text.Text.Length - 1, 1); text.Select(text.Text.Length, 0); } break; case 3: match = Regex.Match(text.Text, isNumber); if (!match.Success) { text.Text = text.Text.Remove(text.Text.Length - 1); text.Select(text.Text.Length, 0); } else MessageBox.Show("Success!!!!!"); break; } }
As you can see, I do char with char until it reaches 3 in length, then I will check the regex.
source share