"Sqlparameter is already contained by another Sqlparameter Collection" --This
is the problem I faced last week while I created two SqlCommand. First one, to
find the variable Id 'a' and second one pass that 'a' to the stored procedure.
The solution, I added the SqlCommand.Parameters.Clear() to the code and the problem gone.
As you can in the code, I created SqlCommand Command and should be destroyed at the end because
C# is the managed language that handles garbage collections.
Code example:
SqlConnection conn =
new SqlConnection(DataAccess.GetConnectionString());
string strSQLCommand =
"select Id from Schools WHERE SchoolName= '" + name + "'";
SqlCommand command =
new SqlCommand(strSQLCommand, conn);
int a = Convert.ToInt32(command.ExecuteScalar());
//write this line of code before using another command execute function
command.Parameters.Clear();
...................................................
...................................................
SqlDataReader rdr = null;
SqlCommand cmd = new SqlCommand("dbo.GetSchoolName", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = a;
rdr = cmd.ExecuteReader();
...................................................
...................................................
Happy Coding !!!