0

I am trying to design an statement in a textbox of a Windows form so that the backcolor changes if the input given is <, >, or == to a given variable.

I've been trying with the if/else if and switch.

private void txtPuntosTotalesAGenerar_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Enter)
        {
            int finalSamplePoints = Convert.ToInt32(Console.ReadLine());
            int try1 = 1500;

            if (finalSamplePoints > try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Orange;
            }
            else if (finalSamplePoints < try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Red;
            }
            else if (finalSamplePoints == try1)
            {
                txtPuntosTotalesAGenerar.BackColor = Color.Green;
            }
        }
    }

With this code I have been able to obtain the red background color, but it is never changing, no matter the values I introduce in the textbox.

RobC
  • 22,977
  • 20
  • 73
  • 80
  • Consider about refreshing/redrawing the window after you change the color. You can try calling this.Invalidate() or this.Refresh() on the form. – Sarker Oct 11 '19 at 09:08

1 Answers1

0

The issue is Console.ReadLine() always gives you 0 , when the Enter Key is pressed .

I think you need to modify the logic like this

private void txtPuntosTotalesAGenerar_KeyPress(object sender, KeyPressEventArgs e)
{

    if (e.KeyChar == (char)Keys.Enter)
    {
        int finalSamplePoints = Convert.ToInt32(txtPuntosTotalesAGenerar.Text);
        int try1 = 1500;

        if (finalSamplePoints > try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Orange;
        }
        else if (finalSamplePoints < try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Red;
        }
        else if (finalSamplePoints == try1)
        {
            txtPuntosTotalesAGenerar.BackColor = Color.Green;
        }
    }
}

Obviously you need to add appropriate validation to make sure any non numeric input is handled appropriately.

Soumen Mukherjee
  • 2,953
  • 3
  • 22
  • 34