1

I am trying to create an INSERT INTO query, that which creates a value in a table with the value null; however, this is not working.

This is the code:

cmd = new SqlCommand("INSERT INTO Questions ([Student_ID],[Teacher_ID],[Question],[Answer],[Answered]) VALUES (@Student_ID,@Teacher_ID,@Question,@Answer,@Answered)", con);

cmd.Parameters.AddWithValue("@Student_ID", FrmLogIn.User_ID);
cmd.Parameters.AddWithValue("@Teacher_ID", cmboxTeacherChoice.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@Question", tbStudentQuestion.Text);
cmd.Parameters.AddWithValue("@Answer", null);
cmd.Parameters.AddWithValue("@Answered", 0);

This code works when a value is put in cmd.Parameters.AddWithValue("@Answer", null); instead of null being there, but I need this value to be null. In the database this variable is saved as a nvarchar(MAX) and is allowed nulls, am I doing something incorrect? Please let me know.

Any answers are appreciated, if I was unclear please inform me, thank you.

3
  • 1
    Possible duplicate of Exception when AddWithValue parameter is NULL Commented May 8, 2017 at 18:49
  • You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results... Commented May 8, 2017 at 19:15
  • IF this value will always be null, why are you putting into the INSERT, you could just remove it from the statement and then not add the corresponding parameter Commented May 8, 2017 at 20:09

1 Answer 1

5

use DBNull.Value instead of null

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

Comments

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.