I have a few similar functions that interact with my SQL server (selects, calls to stored procdures etc.) and all work with the exception of the one below. Each SqlConnection is contained within a using block with the SqlCommand also contained within a using block.
This code is failing when attempting to add the @LastUpdated parameter. I've tried some suggestions I've seen in other posts: cmd.Parameters.Clear(), wrapping in using, etc., but no luck. A few posts with the same error were resolved when duplicate attempts to set the same parameter where found. It's possible I'm missing that but I've looked over this for a few hours, even cleaned the glasses. Any direction would be appreciated.
private void _AddCartItem(bool hasEventInCart, _EventCart cartContents, ref int cartItemId)
{
using (SqlConnection sqlConnection = new SqlConnection(_striMISConnection))
{
sqlConnection.Open();
using (SqlCommand cmd = sqlConnection.CreateCommand())
{
SqlParameter param = new SqlParameter();
cmd.Parameters.Clear();
// add/update CartItem
if (hasEventInCart)
{
// Update item
cmd.CommandText = "SProc2Insert @CartItemId, @ID, 'Event', @Created, @LastUpdated";
param.ParameterName = "@CartItemId";
param.Value = cartItemId;
cmd.Parameters.Add(param);
}
else
{
// add item
cmd.CommandText = "SProc2Update @ID, 'Event', @Created, @LastUpdated";
}
cmd.CommandType = CommandType.Text;
param.ParameterName = "@Created";
param.Value = DateTime.Now.ToString();
cmd.Parameters.Add(param);
param.ParameterName = "@LastUpdated";
param.Value = DateTime.Now.ToString();
**cmd.Parameters.Add(param);**
param.ParameterName = "@ID";
param.Value = this.ID;
cmd.Parameters.Add(param);
if (hasEventInCart)
{
cmd.ExecuteNonQuery(); // do the update
}
else
{
cartItemId = (int)cmd.ExecuteScalar();
foreach (var currentCartEvent in cartContents.CartEvents)
{
if (currentCartEvent.EventCode == this.EventCode)
{
currentCartEvent.CartItemID = cartItemId;
}
}
}
cmd.Parameters.Clear();
}
}
}
sqlCommand.Parameters.Add("@Filename", System.Data.SqlDbType.VarChar, 64).Value = "Foo";. Addingoutputorreturnvalueparameters may be done in a single statement:sqlCommand.Parameters.Add("@Filename", System.Data.SqlDbType.VarChar, 64).Direction = System.Data.ParameterDirection.Output;. It's a bit odd that you are passingDateTimevalues as strings rather thanDateTimeor a more suitable data type (Date,DateTimeOffset, ... .).