Search code examples
c#asp.netrepeater

Multiple delete function deletes only one row in repeater control


i have 2 repeater controls one inside another, actually i am showing contents from two different tables, i have added checkboxes for each row to delete multiple rows using single button click, but after selecting multiple check boxes delete query deletes only one row at a time.i just added checkobx under repeater control, I tried to figure out the exception but stack doesnt show it!! following is my codebehind:

protected void btnDeleteNews_Click(object sender, EventArgs e)
{

    foreach (RepeaterItem item in rptMainBlock.Items)
    {

        if ((item.FindControl("chkDel") as CheckBox).Checked)
        {
            string newsId = (item.FindControl("lblNewsId") as Label).Text;
            cmd = new SqlCommand("DELETE FROM newsImageGal where newsId IN (SELECT newsId from news where newsId=@newsId);DELETE from news where newsId=@newsId", con);
            con.Open();
            cmd.Parameters.AddWithValue("@newsId", newsId);
            cmd.ExecuteNonQuery();

            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", "alert('Selected News Deleted Successfully');", true);
            con.Close();
            Response.Redirect("deleteNews.aspx");

        }
        else
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", "alert('No Data Deleted');", true);
        }
    }

}

Please let me know why this is happening.


Solution

  • The problem is that you are redirecting in the loop with:

    foreach (RepeaterItem item in rptMainBlock.Items)
    {
        // delete ..
        Response.Redirect("deleteNews.aspx");  // aborts this thread and ends the page's life-cycle
    }
    

    I assume that you want to do that only once at the end instead:

    foreach (RepeaterItem item in rptMainBlock.Items)
    {
        // delete ..
    }
    Response.Redirect("deleteNews.aspx");
    

    However, the alert('Selected News Deleted Successfully'); is also pointless when you redirect to another page.