Web Tip: Add Message and Confirmation Boxes Using JavaScript

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Any time I have a Delete or Cancel button, I add a JavaScript confirmation dialog to keep the user from doing something he might regret. In other cases, a simple alert with an OK dialog is sufficient. To save myself some time, I’ve created the following two functions to do this work for me:

public void AddConfirmMessage(WebControl ctl, string message)
{
   ctl.Attributes.Add("onclick", "if ( ! confirm( '"
      + message + "' )) return false; ");
}

public void AddPopupMessage(WebControl ctl, string message)
{
   ctl.Attributes.Add("onclick", "alert( '" + message + "'); ");
}

They accept a generic WebControl object and edit the Attributes collection of that control, which adds the JavaScript code to the control from the code-behind. These functions will work with any control that derives from the WebControl class. Simply pass in the control and the message you want to display, and as long as the user has JavaScript enabled, the messages will appear.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read