2015-03-13 111 views
-1

我知道我的代碼非常糟糕,但我仍然在學習,但我不明白這條消息任何人都可以解釋我去過哪裏錯誤無法投射'system.windows.forms.textbox'類型的對象來鍵入'System.IConvertible'錯誤

private void btnCalculate_Click(object sender, EventArgs e) 
{ 
    //These are my variables which will take form of the values from the database and display whatever the user has input 
    int iDay1, iDay2, iDay3, iDay4, iDay5, iDay6, iDay7; 
    int iScore; 
    iDay1 = Convert.ToInt32(txtBox1); 
    iDay2 = Convert.ToInt32(txtBox2); 
    iDay3 = Convert.ToInt32(txtBox3); 
    iDay4 = Convert.ToInt32(txtBox4); 
    iDay5 = Convert.ToInt32(txtBox5); 
    iDay6 = Convert.ToInt32(txtBox6); 
    iDay7 = Convert.ToInt32(txtBox7); 
    iScore = Convert.ToInt32(iDay1 + iDay2 + iDay3 + iDay4 + iDay5 + iDay6 + iDay7); 
    string Query = "insert into sql370447.calorie (day1, day2, day3, day4, day5, day6, day7) values('" + txtBox1.Text + "','" + txtBox2.Text + "','" + txtBox3.Text + "','" + txtBox4.Text + "','" + txtBox5.Text + "','" + txtBox6.Text + "','" + txtBox7.Text + "');"; 
    MySqlConnection myConn = new MySqlConnection(connStr); 
    MySqlCommand cmdDataBase = new MySqlCommand(Query, myConn); 
    MySqlDataReader myReader; 
    myConn.Open(); 
    myReader = cmdDataBase.ExecuteReader(); 
    //A simple If statement to determine wether the user is healthy or not the users results will change depending on gender 
    if (iScore >= 8000 && iScore <= 10000) 
    { 
     MessageBox.Show("Congratulations you are a Healthy male, your calorie intake is " + iScore); 
    } 
    else if (iScore >= 10001) 
    { 
     MessageBox.Show("You are eating more than you should be you are an unhealthy male, your calorie intake is " + iScore); 
    } 
    else 
    { 
     MessageBox.Show("You are eating way less than the healthy amount, you are an unhealthy male atm your calorie intake is " + iScore); 
    } 
} 
+0

**警告**您的代碼是非常容易受到SQL注入攻擊! – 2015-03-13 19:57:23

+0

你想'textboxN.Text'。 – 2015-03-13 19:57:33

+0

您需要引用文本框的.Text屬性,而不是文本框本身...... – 2015-03-13 19:58:25

回答

3

您當前正在嘗試將文本框自身轉換爲整數。這是行不通的。您需要將文本轉換文本框內:

iDay1 = Convert.ToInt32(txtBox1.Text); 

(ETC)。

你應該絕對肯定停止建立你的SQL雖然。閱讀有關參數化SQL,避免SQL注入攻擊,使您的代碼更易於閱讀並避免轉換問題。

你還應該考慮:

  • 使用數組或其他收集所有這些文本框,所以你可以只循環。
  • 卸下i前綴 - .NET naming conventions特別反對匈牙利命名法
  • 使用int.TryParse代替Convert.ToInt32這樣你就可以檢測無效的輸入,而無需異常
+0

int.Tryparse需要一個參數 – Brett 2015-03-13 20:03:14

+0

@Brett:好的,你仍然需要在'txtBox1.Text'中解析,顯然... – 2015-03-13 20:08:19

0

要訪問一個TextBox提交的文本,你需要看看在屬性Text

iDay1 = Convert.ToInt32(txtBox1.Text);