无法转换类型&system; system.windows.forms.textbox'键入' System.IConvertible'错误

时间:2015-03-13 19:52:58

标签: c# mysql

我知道我的代码真的很糟糕但我还在学习但我不明白这个消息可以解释我哪里出错了

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);
    }
}

2 个答案:

答案 0 :(得分:2)

您目前正在尝试将文本框本身转换为整数。那不行。您需要转换文本框中的文本

iDay1 = Convert.ToInt32(txtBox1.Text);

(等)。

你应该绝对肯定停止构建你的SQL。阅读有关参数化SQL,避免SQL注入攻击,使代码更易于阅读以及避免转换问题。

您还应该考虑:

  • 对所有这些文本框使用数组或其他集合,因此您可以循环。
  • 删除i前缀 - .NET naming conventions明确拒绝匈牙利表示法
  • 使用int.TryParse代替Convert.ToInt32,以便您可以在没有例外的情况下检测无效输入

答案 1 :(得分:0)

要访问TextBox中提交的文本,您需要查看属性Text

iDay1 = Convert.ToInt32(txtBox1.Text);