Johnathan
Johnathan

Reputation: 134

How can I subtract the value of a label with an integer

I have a label set to a value of a number. what I am trying to do is on the click of a button subtract a number from the value of the label. when I try this I get the error below.

Operator '-' cannot be applied to operands of type string.

        DateTime start = dateTimePicker2.Value.Date;
        DateTime end = dateTimePicker1.Value.Date;

        TimeSpan difference = end - start;

        int days = difference.Days;
        int rdays = Convert.ToInt32(Holidays_Number_lbl.Text);
        Holidays_Number_lbl.Text = days.ToString() - rdays.ToString();

Also If I replace the - with a + it works but if the label value is 20 and add 1 get the result 120 instead of 21? not sure why.

Upvotes: 1

Views: 951

Answers (3)

Hamed Moghadasi
Hamed Moghadasi

Reputation: 1673

You can't subtract two variable with string datatype, because - is not defined for string variable. for solve your exception replace below code:

Holidays_Number_lbl.Text = (days - rdays).ToString();

Also you ask:

Also If i replace the '-' with a '+' it works but if the label value is 20 and i add 1 i get the result 120 instead of 21? not sure why.

The + operator is defined for strings variable and when you sum up two string variable the result is concatenation of two variable, for example in your case:

Holidays_Number_lbl.Text = "1" + "20"; //The result become 120

Upvotes: 4

Gabriel Luci
Gabriel Luci

Reputation: 40958

You can't do mathematical operations on strings. So don't convert them to strings until after the subtraction happens.

Holidays_Number_lbl.Text = (days - rdays).ToString();

The reason why + works is because that is the concatenation operator for strings - it is not a mathematical operator in that case.

Upvotes: 3

Felipe Martins
Felipe Martins

Reputation: 184

You're trying to subtract two strings instead of two integers. Try this:

int days = difference.Days;
int rdays = Convert.ToInt32(Holidays_Number_lbl.Text);
Holidays_Number_lbl.Text = (days - rdays).ToString();

Upvotes: 6

Related Questions