• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2797
  • Last Modified:

Need a popup confirm box from codebehind

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
0
md0333
Asked:
md0333
  • 11
  • 7
  • 5
  • +2
2 Solutions
 
Saqib KhanSenior DeveloperCommented:
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()"
0
 
EYoungCommented:
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
0
 
Saqib KhanSenior DeveloperCommented:
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;
 }
}
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
md0333Author 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?
0
 
EYoungCommented:
Did you put the code in your Page_Load Event in the code behind?

Here is an example:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            pnlSummary_Automatic.Visible = True
            srGet_Summary_RunDailyAt()
            txtSummary_ManualDate.Text = FormatDateTime(DateAdd("d", -1, Today), DateFormat.ShortDate)

            pnlDetail_Automatic.Visible = True
            srGet_Detail_RunDailyAt()
            txtDetail_ManualDate.Text = FormatDateTime(DateAdd("d", -1, Today), DateFormat.ShortDate)

            Session("mKey") = ""
        Else
            btnDetail_Delete.Attributes.Add("onclick", "return confirm('Are you sure you want to DELETE this detail record?');")
        End If
    End Sub
0
 
EYoungCommented:
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
0
 
md0333Author 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.
0
 
EYoungCommented:
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.
0
 
md0333Author 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
0
 
md0333Author 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
0
 
EYoungCommented:
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".
0
 
md0333Author 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?
0
 
Saqib KhanSenior DeveloperCommented:
did you look at my example?
0
 
md0333Author 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?
0
 
md0333Author 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.

0
 
Saqib KhanSenior DeveloperCommented:
> 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.
0
 
Saqib KhanSenior DeveloperCommented:
how are you calling the function...?

onClientClick = "return functionNAME()"

keyword return is important.
0
 
md0333Author 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

0
 
Saqib KhanSenior DeveloperCommented:
OnClientClicking="return verifyDelete">


<script>
            function verifyDelete() {
                var btn = s
                var c = confirm("Are you sure you want to delete this Lender?");

                if (c) {
                    __doPostBack("<%=btn.UniqueID%>", "");
                }
                else {
                    return false;
                }
            }
</script>


if  <%=btn.UniqueID%> does not work, then do a VIEW SOURCE, find the ID NAME of button and Paste it in javascript function for testing.
0
 
md0333Author 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.
0
 
Saqib KhanSenior DeveloperCommented:
Asp.net only supports onClientClick event, i am not familiar with telerik and i am not sure if they support OnClientClicking or OnClientClicked events.
0
 
md0333Author Commented:
their controls don't have an OnClientClick... just onClientClicked and onClientClicking...
0
 
CodeCruiserCommented:
Which control is displaying the records? Grid?
0
 
havj123Commented:
Use OnClientClicking event
0
 
md0333Author 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!!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 11
  • 7
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now