C# – Operator ‘*’ cannot be applied to operands of type ‘string’ and ‘int’

cvisual studio 2010

namespace exer4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTotal_Click(object sender, EventArgs e)
        {
            int overtime = Convert.ToInt32(txtHours.Text) - 30;
            int salary = Convert.ToInt32(txtHours.Text)*250;
            double tax = (salary + overtime) * .10;
            int deduction = salary - (300 + 400);

            //operator '>' cannot be applied to operands of type 'string' and 'int'
            if Convert.ToInt32(txtHours.Text > 30)
            {
                lblName.Text = txtName.Text;
                lblSalary.Text = Convert.ToString(overtime *120) + (salary - (deduction - tax)); 


            }
            else
            { 
                // //operator '*' cannot be applied to operands of type 'string' and 'int'
                lblSalary.Text = Convert.ToString(txtHours.Text) * 250;
            }
       }
  }

Best Answer

Your if statement should be

if (Convert.ToInt32(txtHours.Text) > 30)

And the other line should be

lblSalary.Text = Convert.ToString(Convert.ToInt32(txtHours.Text) * 250);

Or better yet convert the txtHours text to an int and keep it in a variable to be reused.

    private void btnTotal_Click(object sender, EventArgs e)
    {
        int hours = Convert.ToInt32(txtHours.Text);
        int overtime = hours - 30;
        int salary = hours * 250
        double tax = (salary + overtime) * .10;
        int deduction = salary - (300 + 400);

        if(hours > 30)
        {
            lblName.Text = txtName.Text;
            lblSalary.Text = ((overtime *120) + (salary - (deduction - tax))).ToString(); 
        }
        else
        { 
            lblSalary.Text = salary.ToString();
        }
   }
Related Topic