3

I want to save NULL in database for column while textbox is empty. Here is my code,

cmd.Parameters.AddWithValue("@RedirectUris", ((RedirectUris.Text == "") ? DBNull.Value.ToString() : RedirectUris.Text));

where RedirectUris is textbox id.
In this scenario database is saving empty value not as NULL. Please help me to do this.

3 Answers 3

4

You can do this:

cmd.Parameters.AddWithValue("@RedirectUris", 
        string.IsNullOrEmpty(RedirectUris.Text) 
        ? (object)DBNull.Value : 
        RedirectUris.Text);

Might make sense to check if the value of the textbox is null or empty

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

1 Comment

It is better because here we do'nt need to create new SqlParameter.
3
cmd.Parameters.Add(new SqlParameter("@RedirectUris", string.IsNullOrEmpty(RedirectUris.Text) ? (object)DBNull.Value : RedirectUris.Text));

Comments

1

You can use the short format:

// update
cmd.Parameters.AddWithValue("@ResponseTimeDays", responseTimeDays ?? Convert.DBNull);

// insert
new SqlParameter("@ResponseTimeDays", cinfo.ResponseTimeDays ?? Convert.DBNull)

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.