Home > Net >  get wrong textbox.TextLength in winforms
get wrong textbox.TextLength in winforms

Time:05-21

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);
    }

CodePudding user response:

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;
        }

    }

CodePudding user response:

Im not sure if trackBox1.TextLength is the proper way to get the length

trackBox1.Text.Length //try this
//and also your event 
private void yourTextBox_TextChanged(object sender, EventArgs e)
{
  
}

CodePudding user response:

Have a look at the Control.KeyPress docs... the event fires after a key has been pressed, but before the character actually enters the textbox. This means that the length you're checking is one less than the length you were expecting (unless the key just pressed was backspace, which KeyPress also catches, in which case it is one greater than the length you were expecting).

  • Related