Passing NULL values to SqlCommand.Parameters.AddWithValue

G

Giammarco

Hi All,

I have the following code:

SqlCommand sqlCmd = new SqlCommand(sqlStatment, dbConn);
sqlCmd.Parameters.AddWithValue("@Name", name);
sqlCmd.Parameters.AddWithValue("@Surname", surname);

If surname is NULL I get the following error message:

Parameterized Query xyz expects parameter Surname which was not
supplied.

Do you know any workaround? I basically would like to pass NULL values
to the SQL statment, instead of writing different SQL statment
depending on what values the user provides.

Thanks,
Giammarco
 
E

em00guy

This may work
C# Solution

sqlCmd.Parameters[0].IsNullable = true;
sqlCmd.Parameters[1].IsNullable = true;

let me know
 
G

Giammarco

Thanks guys,
I've solved in the following way:

SqlCommand sqlCmd = new SqlCommand(sqlStatment, dbConn);
sqlCmd.Parameters.AddWithValue("@Name", name);
sqlCmd.Parameters.AddWithValue("@Surname", surname);
// I have more parameters here

foreach (SqlParameter Parameter in sqlCmd.Parameters)
{
if (Parameter.Value == null)
{
Parameter.Value = DBNull.Value;
}
}

Hope it's the best way to do this!

Regards,
Giammarco Schisani
 
G

Giammarco

Hey,
Just an update on the issue: I am using the following workaround:

private SqlMoney? money;
public SqlMoney? Money
{
get { return money; }
set { money = value; }
}

if (Money != null)
{
sqlCmd.Parameters.AddWithValue("@Money", Money);
}
else
{
sqlCmd.Parameters.AddWithValue("@Money", DbNull.Value);
}


Hope it helps!
Giammarco
 
Joined
Jan 5, 2007
Messages
1
Reaction score
0
sqlCmd.Parameters.AddWithValue("@Surname", ((surname == null) ? (object)DBNull.Value ? (object)surname));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top