I am making a simple email sender and what I want to do is to check if the textbox.text has 14 characters. If it’s 14 – then text turns to green, if less it turns to red. I’ve encountered a problem when I type 14th character. It doesn’t turn green. It does when I type another character which is not shown since I have MaxLength = 14, but I still need to type in that 15th character. Also when I try deleting characters, the string doesn’t turn red with the first deleted char, but after a few. I’ve tried things like Regex and trim() thinking that there might be some special characters but it doesn’t seem to work. I also recorded a video with the issue to make it more describing.
private void trackBox1_KeyPress(object sender, KeyPressEventArgs e)
{
trackBox1.Text = RemoveSpecialCharacters(trackBox1.Text);
trackBox1.Text = trackBox1.Text.Replace("\r\n", "\n");
errorBox.Text = trackBox1.TextLength.ToString();
if (trackBox1.TextLength < 14)
{
trackBox1.ForeColor = Color.Red;
} else if (trackBox1.TextLength == 14)
{
trackBox1.ForeColor = Color.Green;
}
trackBox1.Text.TrimEnd();
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
>Solution :
Instead of using the trackBox1_Keypress put your if statement in the trackBox1_TextChanged event and to count the length of the text you should use trackbox.Text.Length instead of trackbox1.TextLength
Here is a sample snippet int the TextChanged event that changes the color from red to green if the text length is greater than or equal to 14.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length <= 14)
{
textBox1.ForeColor = Color.Red;
}
else
{
textBox1.ForeColor = Color.Green;
}
}