2017-04-12 92 views
-6

我试图编写一个If语句,点击button1时将显示在label1中,textbox1为25或上面“客户可接收£5折购买”,将示出了当50或以上“客户可接收£10关闭购买”运算符'<='不能应用于类型'字符串'和'int'(C#)的操作数

我的代码是如下:使用系统;

using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace If_Statement 
{ 

    public partial class Form1 : Form 
    { 
     int numbera = 25; 
     int numberb = 50; 
     public Form1() 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 

     { 
      if (textBox1.Text <= numbera) 
      { 
       label1.Text = ("Customer can receive £5 off purchase"); 
      } 
      if (textBox1.Text <= numberb) 
      { 
       label1.Text = ("Customer can receive £10 off purchase"); 
      } 

     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 
    } 
} 

想知道我要去哪里错,如果我可以解释为什么以及如何解决它。

在此先感谢。

+1

你需要将其转换为int第一,像这样 - >如果(int.Parse(textBox1.Text)<= numbera){...} –

+1

解析您的输入...快速谷歌搜索将有**完全告诉你**问题是什么...... –

+1

如果第一个“if”陈述是真的,那么第二个陈述永远也是真实的。你需要“其他如果”,而不是第二个“如果”。 – JBrooks

回答

1

你需要比较之前将进入到一个数量值转换:当用户输入了一些诸如“ABC”

private void button1_Click(object sender, EventArgs e) 
    { 
     var number = Double.Parse(textBox1.Text); 
     if (number <= numbera) 
     { 
      label1.Text = ("Customer can receive £5 off purchase"); 
     } 
     else if (number <= numberb) 
     { 
      label1.Text = ("Customer can receive £10 off purchase"); 
     } 
    } 

你应该注意到,代码将打破,因为这不能被解析为号码,因此您需要使用更安全的方式来验证用户输入,如Double.TryParse

相关问题