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):


Thursday, 9 April 2009

Button click event handler fires twice

I had a simple button on a form together with its click event handler. On debugging, I noticed that the event handler was firing twice. After a long investigation, I decided to check the HTTP headers. These revealed that the "Display Page Validation" option I was using in the Tools menu of the Web Dev toolbar in Firefox was the culprit.

When switched on, this runs the handler a second time, submitting the results to a validator at This is something to bear in mind, particularly for code that must only run once, such as handling credit card payments.