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

Asked

Viewed 576 times

2

I’m creating an app on VS2015 Windowsformaplication where I need to change the colors of textbox where the result is greater than, equal to or less than zero(0). This is how I’m working:

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 will need to make this same condition in twenty(20) textbox. There’s an easier way than that?

FORM

1 answer

2


It is possible to catch all the textbox using this function:

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

Just insert your logic into the block, it will change for everyone. 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;
        }
    }
  • Luiz From what I understood the change should be checked in each field individually and each change individually, then and the code makes the change based on only one value

  • I understood that there is a general rule that must be checked in each field, I believe that the solution is.

  • Guys, you didn’t solve the problem because there are two (2) textbox that can’t follow this rule. There’s a way I can make an exception ?

  • This is the way to do the interaction, can you tell me the rule of the other two for me to see what can be done? Logica solves the question problem, because you say "I will need to make that same condition in twenty(20) textbox"

  • I actually used the wrong words but I added an image of the form to try to help with solving my problem. The textbox below product and description cannot be treated with the same condition as the rest.

  • 1

    You can add Name from the textbox and when the name is equal to the ones you want out of the rule you just don’t do anything. Or you can also put the textbox inside a panel and just run to the panel children.

  • I got it!! I’ll try to do the way Voce explained!! Thank you

  • good luck, anything we are here.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.