Wednesday 15 April 2009

SqlParameter is Already Contained in Another SqlParameterCollection

This exception occurred between calls to a method I used to populate a SqlCommand object.

SqlCommand cmd = conn.CreateCommand();

...

foreach (SqlParameter sqlParameter in sqlParameters)
{
cmd.Parameters.Add(sqlParameter );
}


The solution was to clear the parameter collection at the end of the method (in a finally block, actually):

cmd.Parameters.Clear();

No comments: