How to change the color of several textbox by looking at only one condition

2

I'm creating an application in VS2015 WindowsFormAplication where I need to change the colors of the textbox when the result is greater than, equal to or less than zero (0). I'm working as follows:

if (Convert.ToDecimal(tbEntrDiferenca.Text) > 0)
  tbEntrDiferenca.BackColor = Color.Green;
if (Convert.ToDecimal(tbEntrDiferenca.Text) < 0)
  tbEntrDiferenca.BackColor = Color.Red;
tbEst2016Mat.BackColor = Color.Red;
if (Convert.ToDecimal(tbEntrDiferenca.Text) == 0)
  tbEntrDiferenca.BackColor = Color.Yellow;

I'll need to do the same condition in twenty (20) textbox . Is there an easier way than this?

    
asked by anonymous 06.09.2017 / 18:41

1 answer

2

You can get all textbox using this function:

foreach (Control c in Controls)
{
    TextBox tb = c as TextBox;
    if (tb != null)
    {
        //Sua Logica
    }
}

Simply insert your logic inside the block, it will change for all. Something like this would probably work:

 foreach (Control c in Controls)
    {
        TextBox tb = c as TextBox;
        if (tb != null)
        {
            if (Convert.ToDecimal(tb.Text) > 0)
                tb.BackColor = Color.Green;
            else if (Convert.ToDecimal(tb.Text) < 0)
                tb.BackColor = Color.Red;
            else 
                tb.BackColor = Color.Yellow;
        }
    }
    
06.09.2017 / 18:47