-1

i got error when i try to make textbox red if number below 18

can you helping me with that ?

i dont know how to fix the problem

private void textBox1_TextChanged(object sender, EventArgs e)
            {
                double numt = 18;
                if (textBox1.Text <= numt)   ////error here
                {

                    textBox1.BackColor = Color.Red; 
                }
            else
            {
                textBox1.BackColor = Color.White;
            }
NAWAF WABS
  • 27
  • 6
  • 1
    Please don't add the [visual-studio] tag unless your question is actually about the tool itself. Please see: [How do I avoid misusing tags?](https://meta.stackoverflow.com/questions/354427/how-do-i-avoid-misusing-tags) – EJoshuaS - Stand with Ukraine Dec 24 '17 at 06:55
  • its work but if i clear input to enter another number i got "Input string was not in a correct format." – NAWAF WABS Dec 24 '17 at 06:59
  • 1
    _"if i clear input to enter another number i got "Input string was not in a correct format.""_ -- that's a completely different issue, but you can find the answer exactly the same way you _should_ have found the answer to this one: just search Stack Overflow (or the web!) for the exact text of the error message you are getting. – Peter Duniho Dec 24 '17 at 07:14

2 Answers2

0

Convert textBox1.Text to dobule to make the comparison.

   if (Convert.ToDouble(textBox1.Text) <= numt)   
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

You need to convert textBox1.Text to a double with double.Parse(...). You can't "directly" compare strings and doubles because it could result in complete nonsense operations like

if ("dog" <= 18)
{
   // Do whatever
}
else if ("chair" > 2.3)
{
   // ...
}

Clearly, this is complete nonsense. While you may know that textBox1.Text will contain a number, the compiler doesn't know that - the main point is that you could, in principle, have a situation like that.

Incidentally, don't just blindly trust the user to do the right thing. Consider what will happen if the user puts in something other than an integer, and validate it before you try to use it. So really, you don't know that this will result in something sensible - for all you know the user could type something like "dog" or "chair" in the text box, and then you'd have a clearly nonsensical situation like we have above.