2017-04-12 19 views
-6

if文を作成しようとしていますが、button1をクリックするとlabel1に表示されます。上記の「お客様は5ポンドの購入を受け取ることができます」と表示され、50以上の場合、「お客様は10ポンドの購入を受け取ることができます」オペレータ '<='は、 'string'および '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に変換する必要があります - > if(int.Parse(textBox1.Text)<= numbera){...} –

+1

入力を解析します。 **正確に**問題が何であるかを教えてくれました... –

+1

そして最初の "if"ステートメントが真であれば、2番目のステートメントも常に真です。 2番目の「if」ではなく「else 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のようなユーザー入力を検証するより安全な方法で作業する必要があります。

関連する問題