34

I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).

Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.

e.g.

Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)

If actLimit.ToLower() = "unlimited" Then
    ' It's not nulling :(
    dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
    dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If

Is there something I'm missing? Am I doing it wrong?

Community
  • 1
  • 1
RodgerB
  • 8,608
  • 9
  • 36
  • 47

3 Answers3

90

you want DBNull.Value.

In my shared DAL code, I use a helper method that just does:

    foreach (IDataParameter param in cmd.Parameters)
    {
        if (param.Value == null) param.Value = DBNull.Value;
    }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
10

I use a SqlParameterCollection extension method that allows me to add a parameter with a nullable value. It takes care of converting null to DBNull. (Sorry, I'm not fluent in VB.)

public static class ExtensionMethods
{
    public static SqlParameter AddWithNullable<T>(this SqlParameterCollection parms,
            string parameterName, T? nullable) where T : struct
    {
        if (nullable.HasValue)
            return parms.AddWithValue(parameterName, nullable.Value);
        else
            return parms.AddWithValue(parameterName, DBNull.Value);
    }
}

Usage:

string? optionalName = "Bozo";
cmd.Parameters.AddWithNullable("@Name", optionalName);
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
3

Try setting it to DbNull.Value.

Sklivvz
  • 30,601
  • 24
  • 116
  • 172