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 fie
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(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);