c# - 无法将类型 'system.windows.forms.textbox' 的对象转换为类型 'System.IConvertible' 错误

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

最佳答案

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

iDay1 = Convert.ToInt32(txtBox1.Text);

(等)。

不过,您应该绝对停止构建 SQL。了解参数化 SQL,以避免 SQL 注入(inject)攻击,使代码更易于阅读,并避免转换问题。

您还应该考虑:

  • 对所有这些文本框使用数组或其他集合,这样您就可以循环。
  • 删除 i 前缀 - .NET naming conventions特别拒绝匈牙利表示法
  • 使用 int.TryParse 而不是 Convert.ToInt32,以便您可以检测无效输入而不会出现异常

关于c# - 无法将类型 'system.windows.forms.textbox' 的对象转换为类型 'System.IConvertible' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29040850/

相关文章:

c# - 如何从 Xamarin.Forms 中的可移植类库项目调用位于 Android 项目内部的方法?

c# - 如何在不挂 gui 的情况下在 WPF 上运行异步任务

mysql - 执行更新数据库时 MVC5 中的 RenameIndexOperation 错误

mysql - 使用复合键进行数据库复制?

c# - 从日期/时间字符串中删除时间

c# - 是否需要在派生类的定义中指定基类实现的接口(interface)?

c# - Nunit:为特定测试用例添加类别

mysql - 插入另一个MySQL后更新表

php - 不使用 PDO 创建表

mysql - 存在与我找不到的事件相关的语法问题