Click here to Skip to main content
Click here to Skip to main content
Go to top

Easy Confirmation Message for .NET Controls

, 7 Feb 2006
Rate this:
Please Sign up or sign in to vote.
A JavaScript solution for a common routine, especially for those DataGrid/GridView Delete buttons.

Sample Image - confirmation.gif

Introduction

This article describes adding a confirmation message to your server controls (even those inside your DataGrid) with one line of code (if that)!

Background

I participate quite a bit on Experts-Exchange (ASP.NET), and always come across the question of how to attach a confirmation message to a Delete button, such as "Are you sure you want to delete this item?". While this is not a difficult task, it is a somewhat mundane one, and having to add an OnClick event to each Button in a DataGrid gets to be a bit much. Instead, I decided I wanted JavaScript to work for me and so it shall...

Using the code

The first step is create the JavaScript method that will handle all of this.

function confirmDelete(e) {    
    var targ;

    if (!e) var e = window.event;
    targ = (e.target) ? e.target : e.srcElement;
    if (targ.nodeType == 3) targ = targ.parentNode;

    if (targ.id.toLowerCase().indexOf("delete") >= 0) {        
        return confirm("Do you want to delete this item?");
    }
    routeEvent(e);
}

document.onclick = confirmDelete;

The confirmDelete function is executed each time a click event occurs on the page. We then use some fun logic to get by the discrepancies in browsers to find the element that was clicked on. If that element has the word "delete" in it, then we launch our confirmation box with the message we see above.

The next step is to create a server control that gets affected by the logic above.

<asp:Button RunAt="server" ID="MyDeleteButton1" Text="Delete Record" />

This delete button will pop-up the confirmation box simply because we have included the word "Delete" in the ID. No code was required, amazing! We're done.

Now, imagine this with your DataGrid/GridView control; no need to attach that OnClick attribute in your ItemDataBound event, or for ASP.NET 2.0, the OnClientClick. We just throw the word "Delete" in the ID.

<!--<span class="code-comment"> ASP.NET 1.x --></span>

<asp:DataGrid RunAt="server" ID="GridView1">
    <Columns>
        ... your other columns ...
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:LinkButton RunAt="server" 
                       ID="DeleteMe" Text="Remove Row" />
            </ItemTemplate>s
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

<!--<span class="code-comment"> ASP.NET 2.0 --></span>

<asp:GridView RunAt="server" ID="GridView1">
    <Columns>
        ... your other fields ...
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton RunAt="server" 
                       ID="DeleteMe" Text="Remove Row" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

You could place the confirmDelete function at the top of each page that you want to have this functionality.

<script type="text/javascript">
    ... confirmDelete function ...
</script>

Or even better, would be to place it in your JavaScript external script file. Then, you could throw it in your Master Page setup and have this feature on every page.

Another Method to Consider

If we didn't want to base everything on the ID of the server control, we could customize it to be assigned to the CSS class attribute. Using the code below, we can retrieve all elements that have a specified className.

function getElementsByClassName(ClassName,tagName,parentElement){
    var elements=new Array();
    var d=parentElement ? parentElement : document;
    var allElements;

    if(tagName)
        allElements=d.all && d.all.tags(tagName)
        || d.getElementsByTagName && d.getElementsByTagName(tagName);
    else allElements=d.all || d.getElementsByTagName("*");

    for(var i=0,len=allElements.length; i<len; i++)
        if(allElements[i].className.indexOf(ClassName)>=0)
            elements[elements.length]=allElements[i];

    return elements;
}
function assignConfirm(className) {    
    var elements = getElementsByClassName(className);
    
    if (elements && elements.length > 0) {
        for (i=0; i<elements.length; i++) 
            elements[i].onclick = confirmDelete;
    }
}
function confirmDelete() {
    return confirm("Are you sure you want to delete this item?");
}

Then assignConfirm function will get executed on the page load and assign a new confirmDelete function (a much more simplified one) to the onClick event for each matching element (including server controls in a DataGrid). The only thing left to do is call it.

<body onload="assignConfirm('delete');">

Finally, an example server control that utilizes this alternative method...

<asp:LinkButton RunAt="server" ID="lbRemove" CssClass="delete" Text="Remove Item" />

That's it. Now we're able to assign the same functionality as before, but using CSS classes to control which controls get this feature. It'd be very easy to tweak this method to toggle multiple messages by simply changing the CssClass name and assigning a separate confirmDelete function.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Jason Scolaro
Web Developer
United States United States
ASP.NET/VB.NET Developer. Constant contributor to Experts-Exchange in the ASP.NET topic area.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMeysampaknahad10-Nov-11 8:01 
Generalhello Pinmemberaditya_asv7-Sep-07 20:22 
GeneralMuch Simpler and No button PinmemberVEMS16-Jan-07 5:36 
QuestionConfirm Delete action with IE7 PinmemberRlearning8-Nov-06 10:30 
To start with, Thank You for this very handy routine. I have been using this routine (unaltered)in my DataGrid successfully (with IE6) for a long time. Now that I have upgraded to IE7 a problem has shown up. The confirm box comes us as usual, but the event (newWindow) also starts up at the same time before the confirmation box is clicked. Here is the code that sets ups the Delete button for my DataGrid "OnItemDataBound".
 
Button btn = (Button)e.Item.FindControl("deleteBtn");
String argURL = "newWindow('myPage.aspx?tIdA=" +((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString()+ "','wpdtup'); return false;";
btn.Attributes.Add("onclick", argURL);
 
I have set IE7 "tabs" to let IE7 decide if a new tab or new window should be opened. The newWindow routine works fine and only has a problem with this "confirm" routine.
 
Thank you for any ideas you may have.
 
Ray G. --- still learning to get around in ASP.NET.
Questioni need a help from u guys immediately Pinmemberasenthil25-Sep-06 19:57 
GeneralButtonColumn Pinmemberfuhaizah14-Mar-06 17:28 
GeneralRe: ButtonColumn PinmemberKilhoffer30-Mar-06 4:49 
GeneralRe: ButtonColumn PinmemberJason Scolaro30-Mar-06 7:25 
GeneralRe: ButtonColumn PinmemberJason Scolaro30-Mar-06 7:27 
GeneralOther Actions Pinmembermunklefish4-Mar-06 2:46 
GeneralRe: Other Actions PinmemberJason Scolaro4-Mar-06 5:07 
GeneralRe: Other Actions Pinmembermunklefish4-Mar-06 6:44 
QuestionAlternate method: OnClientClick in 2.0?? Pinmemberclausn14-Feb-06 11:52 
AnswerRe: Alternate method: OnClientClick in 2.0?? PinmemberJason Scolaro14-Feb-06 16:36 
Generalredirect issue Pinmembertengtium7-Feb-06 14:43 
GeneralRe: redirect issue PinmemberJason Scolaro7-Feb-06 16:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 7 Feb 2006
Article Copyright 2006 by Jason Scolaro
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid