0

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?

7
  • 2
    Make sure that the text in TxtBoxTopicID is a valid integer Commented Mar 4, 2017 at 16:07
  • I get this exception before the form is shown. i.e when I click on the button which directs me to this page. The exception is thrown without me even adding any integer value at the textbox. Commented Mar 4, 2017 at 16:09
  • 2
    If you have not entered anything yet, the value of the TextBox is null or an empty string, which cannot be converted to int. You should either not call the method when opening the form or fill the textbox with a valid default value Commented Mar 4, 2017 at 16:12
  • Of course!. I am so stupid! Thank you very much my friend Commented Mar 4, 2017 at 16:13
  • By the way, am I using parametrised sql? Commented Mar 4, 2017 at 16:14

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the mistake I made was that I called the function in the "load form" function instead of the button. Thanks, very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.