I've been searching for a couple of hours now and cannot find a solution.
I am inserting some strings into SQL, however on on occasions, the method I use to do this may contain strings that are empty, i.e ""
I therefore want to insert a null value into SQL Server instead.
Firstly I test my method to make sure I am able to insert a DBNull.Value
manually by using the following:
cmd.Parameters.AddWithValue("@surname", DBNull.Value); // THIS WORKS OK
HOWEVER when I try the following below, the method runs without any error exception BUT the SQL Server column does not show a null value, it's just empty with nothing in it:
cmd.Parameters.AddWithValue("@surname", (object)surname ?? DBNull.Value);
I just want an efficient solution without messing about with any more common class extensions and writing lots of extra code. Every answer I see on the forums is just over complicated for what should be such a simple task.
Any ideas? Thanks in advance...
Here is the full method:
public static void AddUserToUserTable(string username,
string forename,
string surname,
string emailAddress,
string password,
string accountActive,
string userGroup)
{
string cmdText1 = "INSERT INTO Users (Username, Forename, Surname, EmailAddress, Password, AccountActive, UserGroup) VALUES (@username, @forename, @surname, @emailAddress, @password, @userGroup, @accountActive)";
try
{
// The using statement will take care of the disposing of the reader and the command object.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(cmdText1, connection);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@forename", forename);
cmd.Parameters.AddWithValue("@surname", surname, null);
cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
cmd.Parameters.AddWithValue("@password", password);
cmd.Parameters.AddWithValue("@userGroup", accountActive);
cmd.Parameters.AddWithValue("@accountActive", userGroup);
connection.Open();
cmd.ExecuteNonQuery();
log.Info("NEW User [" + username + "] Created");
}
}
catch (Exception ex)
{
log.Error(ex);
}
}