emufossum13
emufossum13

Reputation: 407

How can I make a text box that changes it's fore color based on what's entered in c#?

I'm working on a project where I'd like to have a text input box that set's the fore color of the text to black if the number is 0 or greater, and red if it's below 0. This is the code I've got so far, and it's entered under the text box event handler for "TextChanged" so that it'll run every time the text changes. Here is the code,

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.TextLength > 1)
        {
            valueCheck = Convert.ToInt32(textBox1.Text);
        }
        if (valueCheck < 1)
        {
            textBox1.ForeColor = Color.Red;
        }
        else if (valueCheck > 0)
        {
            textBox1.ForeColor = Color.Black;
        }
        else
        {
            textBox1.ForeColor = Color.Black;
        }
        valueCheck = 0;
    }

The problem comes when I enter one number of any kind, it's red. But when I enter a second positive number, it turns black. I'm not quite sure what's going on, I think it might have something to do with the way the code is validating on every pass. If someone could help me out, I would appreciate it.

Upvotes: 0

Views: 159

Answers (2)

sa_ddam213
sa_ddam213

Reputation: 43636

Your first if statement will only set valueCheck if TextLength is greater than 1, not greater than 0.

Example:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.TextLength != 0) // more than 0 characters
    {
        valueCheck = Convert.ToInt32(textBox1.Text);
    }

    if (valueCheck >= 0) // Greater/Equal than 0, Black
    {
        textBox1.ForeColor = Color.Black;
    }
    else // less than 0, Red
    {
        textBox1.ForeColor = Color.Red;
    }

    valueCheck = 0;
}

or

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.TextLength != 0)
    {
        valueCheck = Convert.ToInt32(textBox1.Text);
    }
    textBox1.ForeColor = valueCheck >= 0 Color.Black : Color.Red
    valueCheck = 0;
}

Upvotes: 0

tim
tim

Reputation: 536

if (textBox1.TextLength > 1)

When you enter 1 number of any kind, the length of textBox1 is not greater than 1, so valueCheck is not being set.

Also Convert.ToInt32 can throw exceptions in the case where the user only enters the ( - ) sign.

     private void textBox1_TextChanged(object sender, EventArgs e)
    {
        int valueCheck = 0;
        if (textBox1.TextLength >= 1)
        {
            Int32.TryParse(textBox1.Text, out valueCheck);
        }
        if (valueCheck < 1)
        {
            textBox1.ForeColor = Color.Red;
        }
        else if (valueCheck > 0)
        {
            textBox1.ForeColor = Color.Black;
        }
        valueCheck = 0;
    }

Upvotes: 1

Related Questions