Search code examples
c#arcgisarcobjects

Problem changing condicionally BackColor in a textbox form


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.


Solution

  • 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.