5

This is my Delete function after a click. Can anyone show me how to do a simple confirmation function?

ASP.net C#.

Previously I had this

ScriptManager.RegisterStartupScript(this, 
       this.GetType(),
       "script",
       "confirm('Are you sure you want to Delete Your Discussion?');", 
       true);

but the above code run after the deletion has been made.

protected void lnk_delete_Click(object sender, EventArgs e)
{
    GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
    string fieldID = grdrow.Cells[0].Text;

    string query = "Delete from Comment where DiscussionID=@id";

    SqlCommand cmd = new SqlCommand(query, cn);
    cmd.Parameters.AddWithValue("@id", fieldID);

    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();

    string query1 = "Delete from Discussion where DIscussionID=@id";

    SqlCommand cmd1 = new SqlCommand(query1, cn);
    cmd1.Parameters.AddWithValue("@id", fieldID);

    cn.Open();
    cmd1.ExecuteNonQuery();
    cn.Close();

    GridView1.DataBind();
}
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
WeakTaenie
  • 247
  • 2
  • 6
  • 14
  • You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Jan 29 '15 at 12:10
  • Also, you should show this on the client before you send the request to delete. Don't make it a separate step if you don't really need to. – Patrick Hofman Jan 29 '15 at 12:11

2 Answers2

4

I guess it depends where you're putting your RegisterStartupScript code block. Ideally you want the click confirmation all on the client-side rather than anything server-side.

So on the button the user clicks to delete, you want a client-side click handler (if it's a server-side button, the event is onClientClick) that calls a function that returns the result of the confirm() call. Something like this:

<asp:Button ID="lnk_delete" runat="server" onClientClick="return fnConfirmDelete();" onClick="lnk_delete_Click">Delete</asp:Button>

<script language="javascript" type="text/javascript">
function fnConfirmDelete() {
  return confirm("Are you sure you want to delete this?");
}
</script>

The use of the two return statements ensures that if the user presses cancel the submission doesn't go ahead (i.e. the button click is cancelled).

cf_en
  • 1,661
  • 1
  • 10
  • 18
0

This should help you get it working, the javascript part shouldn't be needed, you can also just use the javascript.

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return confirm('Are you sure?')" />

You can get more information over here: https://forums.asp.net/t/1508094.aspx?How+to+pop+up+a+confirmation+dialog+box+