I have a stored procedure that has a parameter called UserName and in my code behind I have a SqlCommand object that I add the parameters to with the Add method. But for som
You will get this exception if the value of your 'userName' variable is null
If null is valid, then pass 'DBNull.Value' to the db instead:
command1.Parameters.Add(new SqlParameter("@UserName", (userName ?? DBNull.Value));
Try making sure that the command type is set to stored procedure.
mycommand.CommandType = System.Data.CommandType.StoredProcedure;
By default, the CommandText
property needs to contain a complete SQL command, not just the name of the stored procedure.
You can change this by to set the SqlCommand
's CommandType property to StoredProcedure
.
Alternatively, you could explicitly pass the parameters, by changing the CommandText
to "someStoredProcedure @UserName, @ProductCode"
; this is a complete SQL statement and will work with the default CommandType
of Text
.
EDIT: I just tried it, and the only way to get that error message without setting CommandType
to StoredProcedure
(which he did not do) is if CommandText
is EXEC someStoredProcedure
. Passing a null
parameter gives a different error.
Command1.CommandType = System.Data.CommandType.StoredProcedure
This will force the ExecuteReader to perform the exec instead of just trying it as a flat command.