3

please help! I have not idea how to fix this.I am stuck on this and it has been a while. What should this code look like at lease the error is in line 8-10

        int intAmountA = 0;
        int intAmountB = 0;
        int intAmountC = 0;
        decimal decPackageA = 0m;
        decimal decPackageB = 0m;
        decimal decPackageC = 0m;
        decimal decTotal = 0m;

        intAmountA = TxtAmountA.Text;
        intAmountB = TxtAmountB.Text;
        intAmountC = TxtAmountC.Text;

        decPackageA = intAmountA * 150;
        decPackageB = intAmountB * 120;
        decPackageC = intAmountC * 90;

        LblPackageA.Text = decPackageA.ToString("c");
        LblPackageB.Text = decPackageB.ToString("c");
        LblPackageC.Text = decPackageC.ToString("c");

        decTotal = decPackageA + decPackageB + decPackageC;


        LblTotal.Text = decTotal.ToString("c");
jimmy
  • 123
  • 1
  • 1
  • 8

3 Answers3

16

The TxtAmountA.Text is a string. You are attempting to set the variable intAmountA which is an integer to a string value, thus the error. You need to parse the integer out of the string in the textbox.

intAmountA = int.Parse(TxtAmountA.Text);

However, be aware that if what is in TxtAmountA.Text is not something that can be cast to an integer, you will get an exception. That is when you can use the conditional int.TryParse(string value, out integer);

Tommy
  • 39,592
  • 10
  • 90
  • 121
6

You'll want to learn about:

Both are basic task, but are incredibly important to programming.

You have a couple of approaches:

intAmount = Convert.ToInt32(txtAmount.Text);
intAmount = int.Parse(txtAmount.Text);

The easiest approach to cast would be the above. However, the problem will occur when invalid user information may be passed. For instance a user passes example would cause an Exception.

You'll want to sanitize the data. So you could try the following:

int amount;
if(int.TryParse(txtAmount.Text, out amount))
{
     // Properly converted amount to an integer.
}

Another approach could be:

int amount = txtAmount.Text.Where(d => char.IsDigit(d));

The safest and most common would be int.TryParse. But these are all approaches you should look into to properly handle data.

Hopefully this helps you.

Greg
  • 11,302
  • 2
  • 48
  • 79
2
intAmountA = TxtAmountA.Text;
intAmountB = TxtAmountB.Text;
intAmountC = TxtAmountC.Text;

You are assigning string type values to an int type variable.

This will convert the string values into their int type representations. e.g. "1" => 1

intAmountA = int.Parse(TxtAmountA.Text);
intAmountB = int.Parse(TxtAmountB.Text);
intAmountC = int.Parse(TxtAmountC.Text);