简体   繁体   中英

How do I pass a null value to a SqlDataSource that is using a stored procedure?

Using .NET 4 and C#. All of these throw an error:

sdsTypeinfo.SelectParameters.Add("@TypeCode", DbType.Boolean, DBNull.Value);

sdsTypeinfo.SelectParameters.Add("@TypeCode", DBNull.Value);

sdsTypeinfo.SelectParameters.Add("@TypeCode", null);

sdsTypeinfo.SelectParameters.Add("@TypeCode", "");

The error indicates that the procedure is not getting any value at all.

Procedure or function 'Typeinfo' expects parameter '@TypeCode', which was not supplied.

Answer

You don't need the @ in the name of the parameter. This is different than adding parameters when calling the stored procedure using a SqlCommand, in which case you want something like this:

cmd.Parameters.AddWithValue("@TypeCode", DBNull.Value);

Also, DBNull.value is an acceptable parameter in the above, but the accepted NULL value when adding SelectParameters to an SqlDataSource is simply "null".

There should be an option when adding a parameter to convert empty string to null.

<SelectParameters>
    <asp:ControlParameter ControlID="lstCategories" Name="ProductSubcategoryID" ConvertEmptyStringToNull="true" PropertyName="SelectedValue" />
</SelectParameters>

Since you're using a stored procedure, you'll want to make the parameter optional:

@SomeParm INT = NULL

you can try like this...

    string x = null;
command.Parameters.AddParameter(
     new SqlParameter("@column", (object)x ?? DBNull.Value);

would give you a parm with a value of DBNull.Value, but

string x = "A String";
command.Parameters.AddParameter(
     new SqlParameter("@column", (object)x ?? DBNull.Value);

In your stored procedure set the parameter to have a value eg

@TypeCode = '' 

or if its an int

@typecode = 1

etc you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM