-2

I need to display a certain number on a label when the user input is between >=0 and <= 1. User input is a string and I need the numbers between to be a decimal or double. Obviously I can't compare the two like I did because the operators can't compare a string and decimal, double, or int.

private void voltageTextBox_TextChanged(object sender, EventArgs e)
{
    var RTPower = powerTextBox.Text;
    powerTextBox.CharacterCasing = CharacterCasing.Upper;

    if (RTPower >= 0 && <= 1)
    {
        displayLabel4.Text = "1";
    }
}

Error: Operator '>=' cannot be applied to operands of type 'string' and 'int'

Error: Operator '<=' cannot be applied to operands of type 'string' and 'int'

How can I make that if statement work? Do I have to keep it as a string, display it in label, convert the label to an integer then re-display it? I know I can make that work, but that is far too complicated. I just need an easier way to do this.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
Justin Dosaj
  • 61
  • 10

2 Answers2

1
int RTPower = Int32.Parse(powerTextBox.Text);

or for decimal values

decimal RTPower = Decimal.Parse(powerTextBox.Text);

You need to convert the value from a string to an int.

Also, I assume you are new to c# - my advice would be to avoid using var and explicitly declare your variables. It will make things clear and easier for you to learn and understand.

Boots
  • 181
  • 1
  • 6
0

You can convert to int like

int x = Int32.Parse(RTPower);

then you can compare x.


If, however, you know that the user input will be between [0, 9] then you could use

if(RTPower >= "0" && <= "1")

because strings are compared lexicographically so "1" is under "9" but "10" is under "2".

The first way is much better though, because it works for all numerical user inputs

Olivier Poulin
  • 1,778
  • 8
  • 15
  • I need it to compare to decimal though and read 0. The first answer you gave me doesn't work when I start inputing values like 0.1, .72, 0.59 – Justin Dosaj Jul 21 '15 at 18:52