Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.Net Parameters.AddWithValue rejecting null value for parameter

I am populating tables using a stored procedure. The table allows a 'null' for the middle initial of the name, but I'm getting the following error message:

Procedure or function 'uspInsertPersonalAccountApplication' expects parameter '@MiddleInitial', which was not supplied.

Thanks in advance!

   public void ProcessForm(string[] InputData)
    {
        string ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AssociatedBankConnectionString"].ToString();

        SqlConnection conn = new SqlConnection(ConnString);
        SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplication", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@AccountType", "Savings");
        cmd.Parameters.AddWithValue("@AccountSubType", "Savings");
        cmd.Parameters.AddWithValue("@ExistingCustomer","No");
        conn.Open();
        cmd.ExecuteNonQuery();

        conn.Close();
    }
like image 861
Susan Avatar asked Mar 01 '12 14:03

Susan


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

You can add to project and use following extension method:

public static SqlParameter AddWithValueSafe(this SqlParameterCollection parameters, string parameterName, object value)
{
    return parameters.AddWithValue(parameterName, value ?? DBNull.Value);
}
like image 109
Yuriy Rozhovetskiy Avatar answered Oct 01 '22 22:10

Yuriy Rozhovetskiy


There are two options here:

Modify you stored procedure and make @MiddleInitial param optional (which is currently not optional that's why error is thrown)

@MiddleInitial nvarchar(10) = NULL

Or add following line to your code:

cmd.Parameters.AddWithValue("@MiddleInitial", null);
like image 43
Marcin Avatar answered Oct 01 '22 22:10

Marcin