Wednesday, March 25, 2009

C# ASP .NET web form confirmation dialog box

I didn't realize just how simple it was to include a confirmation dialog box in a C# .NET web form. This is very useful for avoiding incorrect submissions, or those pesky accidental Enter press submissions. Here's how you can do it:

Assuming you have a Button control defined in your form, and lets say its name/ID is Button1. Button1 is also your form submission button. If you want to provide the user a confirmation box to make sure they mean to submit, you can add a single line of code to the Page_Load section of the code-behind file.

protected void Page_Load(object sender, EventArgs e)

Button1.Attributes.Add("onclick", "return confirm('Ok to submit?');");


By adding the "onclick" attribute, this will produce a dialog box with the text "Ok to submit?", with buttons for Ok and Cancel. If the user clicks Ok, the form will continue processing the submission. If they click Cancel, the submission doesn't happen and they can fix their info before submitting.

I added the if(!IsPostBack) so the Page_Load only processes this once. Otherwise it would add the attribute each time the page was posted back to the server. It's not that it would cause any major issues, but the more efficient the code, the better off you'll be. I found it at, and they had other options to consider if you're interested in more information.

1 comment:

Anonymous said...

The Kettic Message Box control is able to add confirmation dialog to Windows application.