This piece of code is a lot if/else
and I want to know if it can be simplified to a handful of lines. The code works perfectly fine, but I prefer to have a more efficient and cleaner way.
if (textBox_naam.Text.Length < 3)
{
textBox_naam.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
textBox_naam.BackColor = Color.White;
}
if (textBox_email.Text.Length < 5)
{
textBox_email.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
textBox_email.BackColor = Color.White;
}
if (textBox_body.Text.Length < 20)
{
textBox_body.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
textBox_body.BackColor = Color.White;
}
Your easiest bet (no tricks involved!) would be:
SetBackColor(textBox_naam, 3, GOOD_COLOR, BAD_COLOR);
SetBackColor(textBox_email, 5, GOOD_COLOR, BAD_COLOR);
SetBackColor(textBox_body, 20, GOOD_COLOR, BAD_COLOR);
with a method SetBackColor
defined like this:
public void SetBackColor(TextBox tb, int minLength, Color goodColor, Color badColor)
{
tb.BackColor = tb.Text.Length < minLength ? badColor : goodColor;
}
You can use the ternary if then else operator
textBox_naam.BackColor = textBox_naam.Text.Length < 3 ? Color.FromArgb(205, 92, 92) : Color.White;
This isn't any more efficient, but will use less lines of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With