This is my code for which I am getting the above said error when trying to delete the tournament. Since Tournament is associated with an image, the code calls the ImageDeletion function first and then the tournament count function before deleting the whole tournament.
protected void LVTournament_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
if (Session["TournId"] != null)
{
int ClubId = Convert.ToInt32(Request.Cookies["ClubDetails"]["ClubId"]);
int TournId = Convert.ToInt32(Session["TournId"]);
SqlConnection con1 = new SqlConnection(constr);
SqlConnection con2 = new SqlConnection(constr);
ImageDeletion(TournId);
string querydelTour = "DELETE FROM Tournaments WHERE TournamentId = @TournId";
SqlCommand cmd1 = new SqlCommand(querydelTour, con1);
cmd1.Parameters.AddWithValue("@TournId", TournId);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
UpdateTourCount(ClubId);
ClientScript.RegisterStartupScript(Page.GetType(), "Success", "<script language='javascript'>alert('Tournament Deleted...')</script>");
Response.Redirect("TournamentView.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "Popup", "SessionExpires();", true);
return;
}
}
The Image Deletion function is
private void ImageDeletion(int TournId)
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmdchk = new SqlCommand("SELECT count(*) Valid FROM TournamentImages WHERE TournamentId= @TournId");
cmdchk.Connection = con;
cmdchk.Parameters.AddWithValue("@TournId", TournId);
con.Open();
int Count = (int)cmdchk.ExecuteScalar();
for (int i = 0; i <= Count; i++)
{
string query = "SELECT ImagePath FROM TournamentImages WHERE TournamentId = @TournId";
SqlCommand cmddel = new SqlCommand(query, con);
cmddel.Parameters.AddWithValue("@TournId", TournId);
SqlDataReader reader = cmddel.ExecuteReader();
while (reader.Read())
{
string FilePath = reader[0] as string;
string path = Server.MapPath(FilePath);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
}
con.Close();
}
And the tournament count function is
protected void UpdateTourCount(int ClubId)
{
SqlConnection con = new SqlConnection(constr);
string Query = "UPDATE TournamentCount SET Count = Count + 1 WHERE ClubId =@ClubId";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.Parameters.AddWithValue("@ClubId", ClubId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I have close the connections then and there and still I am getting this error.
Kindly mention me where am I making the mistake. Thanks in advance
What I have tried:
I have tried giving each connection with different names and also
MultipleActiveResultSets=True;
.
None of them are working.