We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Need a popup confirm box from codebehind

md0333
md0333 asked
on
Medium Priority
3,076 Views
Last Modified: 2012-05-11
I have a sub in my VB.Net page that deletes records... I want a confirm box to ask if they are sure prior to the rest of the code running. I know it needs to come from javascript but I don't know how to get the answer 'OK' or 'Cancel' back (in codebehind) and move on from there.

    Protected Sub deleteRecord()

'I want to add a confirm box here and if the user selects 'OK' then continue the rest of the code.

        Dim conn As SqlConnection = New SqlConnection
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("FT").ConnectionString
        conn.Open()

        Dim sSQL As String = "DELETE FROM..."

        Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

        With cmd.Parameters
            .Add(New SqlParameter("@****", cboLenders.SelectedValue))
        End With

        cmd.ExecuteNonQuery()

        cmd.Dispose()
        conn.Dispose()


    End Sub

Open in new window


Thanks
Comment
Watch Question

Saqib KhanSenior Developer

Commented:
actually you should add popup right after user HITS the Delete Button, if user hits OK then force the postback OTHERWISE do a return false within javascript to stop the page from reloading,

onClick="return functionFORconfirm()"

Commented:
What I have done is to add the following code to the code behind section in the Page_Load:

If IsPostBack Then
   btnDetail_Delete.Attributes.Add("onclick", "return confirm('Are you sure you want to DELETE this detail
record?');")
End If
Saqib KhanSenior Developer

Commented:
BTW something like this in javascript..


function functionFORconfirm() {

 var c = confirm("you want to delete");

 if(c) {
__doPostBack('Id_OF_Control (Button)','')
 } else {
   return false;
 }
}

Author

Commented:
@EYoung... that gets the popup to come up but if the user hits cancel it still runs the code and deletes the record... what am I missing?
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
And here is my delete event code in the code behind:

    Protected Sub btnDetail_Delete_Click(sender As Object, e As System.EventArgs) Handles btnDetail_Delete.Click
        DataSource_CWDW_Retail_Detail.DeleteCommand = "DELETE ReportRecipients WHERE RecipientEmail = '" & Trim(txtDetail_EmailAddress.Text) & "'"
        DataSource_CWDW_Retail_Detail.Delete()
        gridDetail_StoresRetail.DataBind()
        gridDetail_StoresRetail.SelectedIndex = -1
        srDetail_ClearFields()
    End Sub

Author

Commented:
Yes... That's what I have (and the message pops up correctly) but when I hit cancel the delete event continues to run and delete the record.

I just left the office for a couple of hours. When I get back I will copy what I've done.

Commented:
1.  Here is my asp code:

                            <asp:Button ID="btnDetail_Delete" runat="server" Text="Delete" Height="30px" Width="70px"
                                style="position:absolute; top:360px; left:220px"
                                ToolTip="Click to remove this recipient from the distribution list for this Detail report" />

2.  I am using vs 2010 vb asp.net but it should be the same for 2008.

3.  I am using AJAX controls and have this near the top of my asp page:

     <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

4.  As long as you put this line:

  btnDetail_Delete.Attributes.Add("onclick", "return confirm('Are you sure you want to DELETE this detail record?');")

   in the code behind Page_Load event and in the IsPostBack section as shown above, then it should work.

Author

Commented:
Mine looks the same unless I'm missing something... I am also using VS2010 VB w/Ajax.

.asp
<telerik:RadButton ID="cmdDelete" runat="server" Text="Delete"
      Width="140px">
</telerik:RadButton>

codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     If Not Page.IsPostBack Then
            Session("bAddUser") = "False"
            loadRegions(Session("CompanyID"))
            sqlProducts.UpdateParameters("CreateDate").DefaultValue = CType(Now(), DateTime)
            sqlProducts.UpdateParameters("ModifyDate").DefaultValue = CType(Now(), DateTime)
            loadSecurity()
        Else
            cmdDeleteLender.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this Record?');")
        End If
End Sub


Protected Sub deleteRecord() Handles cmdDelete.Click

        Dim conn As SqlConnection = New SqlConnection
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("FT").ConnectionString
        conn.Open()

        Dim sSQL As String = "DELETE FROM..."

        Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

        With cmd.Parameters
            .Add(New SqlParameter("@****", cboLenders.SelectedValue))
        End With

        cmd.ExecuteNonQuery()

        cmd.Dispose()
        conn.Dispose()

    End Sub

Author

Commented:
copy/paste correction

Mine looks the same unless I'm missing something... I am also using VS2010 VB w/Ajax.

.asp
<telerik:RadButton ID="cmdDelete" runat="server" Text="Delete"
      Width="140px">
</telerik:RadButton>

codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     If Not Page.IsPostBack Then
            Session("bAddUser") = "False"
            loadRegions(Session("CompanyID"))
            sqlProducts.UpdateParameters("CreateDate").DefaultValue = CType(Now(), DateTime)
            sqlProducts.UpdateParameters("ModifyDate").DefaultValue = CType(Now(), DateTime)
            loadSecurity()
        Else
            cmdDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this Record?');")
        End If
End Sub


Protected Sub deleteRecord() Handles cmdDelete.Click

        Dim conn As SqlConnection = New SqlConnection
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("FT").ConnectionString
        conn.Open()

        Dim sSQL As String = "DELETE FROM..."

        Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

        With cmd.Parameters
            .Add(New SqlParameter("@****", cboLenders.SelectedValue))
        End With

        cmd.ExecuteNonQuery()

        cmd.Dispose()
        conn.Dispose()

    End Sub

Commented:
My delete procedure code starts with:

Protected Sub btnDetail_Delete_Click(sender As Object, e As System.EventArgs) Handles btnDetail_Delete.Click

The "Protected Sub" name is the same as the "Handles" name in my procedure above.  You might try changing yours to match.


Currently yours starts with:

Protected Sub deleteRecord() Handles cmdDelete.Click

and the two names are different, i.e. "deleteRecord()" and "cmdDelete".

Author

Commented:
I changed it to

Protected Sub cmdDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDelete.Click

still runs the code after cancel. I didn't think the name of the sub made a difference because the Handles clause gets the name of the asp object. (which is cmdDelete)

What I'm not seeing in the code is where is it determined if the user selects OK or Cancel? To me, it just looks like it opens the form and when the form is closed it continues to move along. What (on Cancel) stops the button postback from occurring?
Saqib KhanSenior Developer

Commented:
did you look at my example?

Author

Commented:
Yes... but I'm not great with javascript so had a few questions about the code you put in your last post...

function functionFORconfirm() {

 var c = confirm("you want to delete");

 if(c) {
__doPostBack('Id_OF_Control (Button)','')
 } else {
   return false;
 }
}

1. In my button, do I use the onClientClick to call your routine and keep the server code the same?
2. Is "_doPostBack" actual code or directions on what to do?

Author

Commented:
OK... I got your code to work the same as the other. It pops up the Confirm box but if I hit cancel it continues to run the code... and delete the record.

Saqib KhanSenior Developer

Commented:
> In my button, do I use the onClientClick to call your routine and keep the server code the same?

Correct.

> Is "_doPostBack" actual code or directions on what to do?

that is a built-in function provided by ASP.NET in all of your pages, if you do a view source on your page you will see it there

on basicly onClientClick you are invoking a client side javaScript function (Within <Script> Tags), that function checks for either OK or Cancel was Clicked.
Saqib KhanSenior Developer

Commented:
how are you calling the function...?

onClientClick = "return functionNAME()"

keyword return is important.

Author

Commented:
here is what I used

javascript
            function verifyDelete(s, e) {
                var btn = s
                var c = confirm("Are you sure you want to delete this Lender?");

                if (c) {
                    __doPostBack(btn.UniqueID, '');
                } 
                else {
                    return false;
                }
            }

Open in new window


aspx
                               <telerik:RadButton ID="cmdDelete" runat="server" Text="Delete" 
                                    Width="140px"  OnClientClicking="verifyDelete">
                                    <Icon PrimaryIconCssClass="rbRemove" />
                                </telerik:RadButton>

Open in new window

Senior Developer
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
OK... I think this may be a problem with the Telerik controls I'm using... if I use your code it locks up the comboboxes on my page. Weird.

I've tried:
OnClientClicking="return verifyDelete">
OnClientClicked="return verifyDelete">
OnClientClicked="if (!confirm('Are you sure?')) return false;">

and all of these lock up my comboboxes... if I change it to
OnClientClicked="verifyDelete">
the comboboxes work fine but the code doesn't stop the postback.

I'm going to create a support ticket and will get back with you... thanks.
Saqib KhanSenior Developer

Commented:
Asp.net only supports onClientClick event, i am not familiar with telerik and i am not sure if they support OnClientClicking or OnClientClicked events.

Author

Commented:
their controls don't have an OnClientClick... just onClientClicked and onClientClicking...
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
Which control is displaying the records? Grid?

Commented:
Use OnClientClicking event

Author

Commented:
OK... got the answer from Telerik. The control changes the way the process works...

had to use: OnClientClicking="verifyDeleting"

and the javascript is:
function verifyDeleting(sender, args) {
     args.set_cancel(!window.confirm("Are you sure you want to delete this Lender?"));
}

going to split the points because EYoung & adilkhan both gave good working examples for ASP controls...

Thank you!!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.