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]

C# Code:

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));
cmd.Connection = connection;

An unhandled exception of type ‘System.FormatException’ occurred in mscorlib.dll

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. Am I using parametrised 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

Possible solutions:

  • Do not call the method during startup of the form
  • Fill the TextBox with a valid default value

To answer the second part of the question: Yes, you are already using a parameterized query.