[英]input string was not in a correct format error in C#
I am trying to add the following details into the Database table.我正在尝试将以下详细信息添加到数据库表中。 The question.问题。 the answer and the topicID[int]答案和主题 ID[int]
C# Code: C# 代码:
private void AddingQuestions()
{
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=root;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO questions (question, answer, topicID) VALUES (@Questions, @Answers, @TopicID);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Questions", TxtBoxQuestion.Text);
cmd.Parameters.AddWithValue("@Answers", TxtboxAnswer.Text);
cmd.Parameters.AddWithValue("@TopicID", Convert.ToInt32(TxtBoxTopicID.Text));
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
}
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll mscorlib.dll 中发生类型为“System.FormatException”的未处理异常
Additional information: Input string was not in a correct format.附加信息:输入字符串的格式不正确。
at the Line:在线:
cmd.Parameters.AddWithValue("@TopicID", Convert.ToInt32(TxtBoxTopicID.Text));
Furthermore: I know its good practise to use parametrised sql to avoid sql injections.此外:我知道使用参数化 sql 来避免 sql 注入的好习惯。 Am I using parametrised sql?我在使用参数化的 sql 吗?
As discussed in the comments, the problem is that you try to convert the Value of a TextBox that actually does not have a value (it is null or empty string) during opening of the Form正如评论中所讨论的,问题是您尝试在打开表单期间转换实际上没有值(它是 null 或空字符串)的 TextBox 的值
Possible solutions:可能的解决方案:
To answer the second part of the question: Yes, you are already using a parameterized query.回答问题的第二部分:是的,您已经在使用参数化查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.