SnapShot
SnapShot

Reputation: 35

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));
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
}

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?

Upvotes: 0

Views: 577

Answers (1)

Flat Eric
Flat Eric

Reputation: 8111

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.

Upvotes: 1

Related Questions