Click here to Skip to main content
Click here to Skip to main content

A Simple ASP.NET Server Control: Message Box & Confirmation Box

, , 2 Sep 2004
Rate this:
Please Sign up or sign in to vote.
An article on creating a simple ASP.NET server control that functions as Message Box and Confirmation Box


In web-based applications, Message Box, Confirmation Box etc are used very often to alert user or to ask user's confirmation for some important operation. In web forms, these popup boxes are usually implemented using JavaScript that runs on client side, for example, using alert, confirm etc functions. A disadvantage of this solution is that the popup time of those prompt boxes is statically specified on client side at design time, so they can't be flexibly used on server side like a server side component, which is very inconvenient, especially for complicated commercial applications that have very complex business logic but need to provide friendly user interface.

In Lee Gunn's article "Simple Message Box functionality in ASP.NET", he only solved the Message Box problem, but didn't mention Confirmation Box issue. In this article, we will introduce a simple but very practical server control that can perform the functionality of either Message Box or Confirmation Box. What's more, the configuration and use of this server control is also very easy.

Using the code

To use the server control in the code, first you need to add the server control as a .NET Framework Components to your web application. Detailed steps are: Right click the "components" tab in the toolbox, click "Add/Remove Items", there's a window pop up, in the .NET Framework components tab, click "Brower", and select and add the server control executable from where you kept in your computer. The file name is msgBox.dll. Then, drag and drop the server control to your web form. (Please note here: please put the server control at the last position of the web form, else there will be some unexpected result).

The following is WebForm1.aspx code with the server control inside.

<%@ Register TagPrefix="cc1" Namespace="BunnyBear" Assembly="msgBox" %>
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
  AutoEventWireup="false" Inherits="msgbox_app.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="" 

<form id="Form1" method="post" runat="server">
<asp:Button id="Button1" runat="server" Text="Submit"></asp:Button>
<asp:TextBox id="TextBox1" runat="server" Width="232px" Height="32px">
<cc1:msgBox id="MsgBox1" runat="server"></cc1:msgBox>

Suppose such a simple scenario: when you click Button1, you will pop up a Message Box if no text input in TextBox1, but if there's input in TextBox1, you will pop up a confirmation box to ask user if he wants to continue. Corresponding Button-Click event handling code is listed as below.

To pop up a Message Box , you only need to call alert(string msg) method of the server control. It is very easy so don't explain here. We will mainly introduce how to pop up a confirmation box here. The second parameter of method confirm(string msg, string hiddenfield_name) is the name of a hidden field element of the web form which the server control also belongs to. You don't need to explicitly create the hidden field component, the server control will create one for you using the hidden field name you provide, but you need to provide a unique hidden field name that differentiate itself from the other components in the web form. The original value of the hidden field is "0". When the user click "ok" to confirm the operation, the server control will change the value of the previously specified hidden field value from "0" to "1".

private void Button1_Click(object sender, System.EventArgs e)
  //for the page with only one form
  if(TextBox1.Text!=null && TextBox1.Text!="")
     MsgBox1.alert("Please input something in the text box.");
     MsgBox1.confirm("Hello "+ TextBox1.Text + 
          "! do you want to continue?", "hid_f");

If the user answers the confirmation box by clicking either "OK" or "CANCEL" button, the web page will be posted back, so you need to write corresponding code to capture and process that. That piece of code is usually put in the Page_Load() method of the code behind of the ASPX page. By checking if the value of the hidden field element of the form is changed to "1", which means the user confirms, you can put corresponding processing code as below. Please don't forget to reset the hidden field value back to original value "0", otherwise something will be wrong the next time to invoke the confirm box.

private void Page_Load(object sender, System.EventArgs e)

    if(Request.Form["hid_f"]=="1")   //if user clicks "OK" to confirm 
          //Reset the hidden field back to original value "0"

        //Put the continuing processing code 
        MsgBox1.alert("hello " + TextBox1.Text); 


That's it. Very easy and simple, isn't it? All above C# code is within WebForm1.aspx.cs, the code behind of WebForm1.aspx.

The other thing we need to mention is that in above scenario, we assume that WebForm1.aspx only includes ONE web form. Actually, in ASP.NET, each ASPX page only supports one web form server control, so for most cases, above solution is enough. However, there're also very few cases such that in some ASPX page, there's one web form server control and also other traditional HTML form, i.e., the page includes more than one web forms. Using the msgBox server control can also easily solve this issue. What you need to do is to put the msgBox as an element of the server control web form and this web form should be the first form in the web page. The rest process remains the same. The WebForm2.aspx in the demo project shows this case.
The normal HTML form element is not a server control so it can't post back to the code behind of the ASPX page, so you need to write the processing code somewhere else, in the following sample, those processing code is shown in the same WebForm2.aspx page.

<%@ Register TagPrefix="cc1" Namespace="BunnyBear" Assembly="msgBox" %>
<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" 
  AutoEventWireup="false" Inherits="msgbox_app.WebForm2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

//for the page with more than one forms
"Button2 clicked. Please input something in the second text box.");
MsgBox1.confirm("Button2 clicked. Hello "+ 
  Request.Form["text1"].ToString() + "! do you want to continue?", "hid_f2");

if(Request.Form["hid_f2"]=="1") //if button2 is clicked and user confirmed
 //Your processing code here
 MsgBox1.alert("Button2 Clicked and user confirmed. Hello " 
  + Request.Form["text1"]);
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<body MS_POSITIONING="GridLayout">
<DIV style="LEFT: 56px; WIDTH: 512px; 
POSITION: absolute; TOP: 136px; HEIGHT: 128px"
<FORM id="Form1" method="post" runat="server">
<asp:button id="Button1" runat="server" Text="Button1">
</asp:button><asp:textbox id="TextBox1" runat="server" 
Width="232px" Height="40px">
</asp:textbox><cc1:msgbox id="MsgBox1" runat="server"></cc1:msgbox></FORM>
<FORM id="Form2" method="post">
<INPUT id="btn" type="submit" value="Button2" name="btn" runat="server"> 
<INPUT id="text1" style="WIDTH: 224px; 
HEIGHT: 31px" type="text" size="32" name="text1"

About msgBox Server Control

The basic mechanism of msgBox server control is actually very simple, and may need better improvement later, but the convenience it brings is also tremendous. The key thing inside the server control is that it outputs the corresponding JavaScript code to HTML during the server control rendering phase, and it utilize JavaScript to change the value of the hidden field that it creates so that the hidden field can work as a tag representing the user's behavior (user's answer to the confirmation box). Please note, the hidden field control is a pure HTML element, NOT a server control. Only in this way, it can be accessed in JavaScript code, and its value will also be posted to server when the form is posted. The following is the source code for msgBox server control, it's pretty easy for you to understand if you know a little of ASP.NET server control life cycle.

Source Code

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;

namespace BunnyBear
/// <summary>
/// Summary description for WebCustomControl1.
/// </summary>
ToolboxData("<{0}:msgBox runat="server"></{0}:msgBox>")]
public class msgBox : System.Web.UI.WebControls.WebControl
//private string msg;
private string content;


public void alert(string msg)
string sMsg = msg.Replace( "\n", "\\n" );
sMsg = msg.Replace( "\"", "'" );

StringBuilder sb = new StringBuilder();

sb.Append( @"<script language="'javascript'">" );

sb.Append( @"alert( """ + sMsg + @""" );" );

sb.Append( @"</script>" ); 


//confirmation box
public void confirm(string msg,string hiddenfield_name)
string sMsg = msg.Replace( "\n", "\\n" );
sMsg = msg.Replace( "\"", "'" );

StringBuilder sb = new StringBuilder();

sb.Append( @"<INPUT type=hidden value='0' name='" + 
  hiddenfield_name + "'>");

sb.Append( @"<script language="'javascript'">" );

sb.Append( @" if(confirm( """ + sMsg + @""" ))" );
sb.Append( @" { ");
sb.Append( "document.forms[0]." + hiddenfield_name + ".value='1';" 
  + "document.forms[0].submit(); }" );
sb.Append( @" else { ");
sb.Append("document.forms[0]." + hiddenfield_name + ".value='0'; }" );

sb.Append( @"</script>" );


/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)


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


About the Authors

Ning Liao

United States United States
No Biography provided

Liang Yang

United States United States
No Biography provided

Comments and Discussions

QuestionRequest.Form("hid_f").Replace("1","0") doesn't work in PinmemberSravan Vadlamani13-Mar-14 15:48 
QuestionNot working in Master Page. PinmemberCheng Bunhok2-Dec-12 22:05 
QuestionCan I use event of OK button to refresh the page PinmemberChandra Pathak13-Sep-12 2:39 
GeneralVey Usefull Artical Pinmembernarasappacj12-Jul-12 21:29 
GeneralMy vote of 4 PinmemberRasheed kh. salem1-Apr-12 2:25 
QuestionThank you Pinmemberdariush_hk14-Mar-12 14:24 
Bugdoesnot work on masterpage Pinmemberhakimji29-Feb-12 0:40 
QuestionHow can i use it with masterpage ? PinmemberRenoMarseille17-Jul-11 7:12 
GeneralMy vote of 1 PinmemberSyed Javed4-Jul-11 7:31 
GeneralMessageBox ConformationBox Pinmembergmangrant9-Dec-10 11:23 
Generalnice dll and it is working. PinmemberC#Coudou26-Nov-10 14:22 
right click on your toolbox then click choose item then browse the msgBox.dll.
just drag and drop the msgbox control from your toolbox to your designer. it works in and
one question: how to avoid postback? if you click ok button. it will refresh entire page.
C# コードMicrosoft End User


The best things in life are free

GeneralIts is working in my envirnment project.. Thank you Soooooooooooo.... Much. Pinmembersixthplanets13-Oct-10 6:49 
GeneralContent page not working Message Box & Confirmation Box Pinmemberibsaravanan7-Jul-10 3:12 
GeneralNasted master page Message Box & Confirmation Box not working Pinmemberibsaravanan7-Jul-10 1:23 
QuestionWill work without Postback? PinmemberRawler19-Nov-09 7:19 
QuestionHow to deploy this control on a webserver? Pinmemberbob Hart 12-Aug-09 9:15 
QuestionIt works but... [modified] Pinmemberylautan17-Jul-09 7:22 
Questionnot sure how to use the hidden field [modified] PinmemberJohn Doe111114-Jul-09 11:19 
GeneralIt is Fantastic But I Have a problem Pinmemberwailalbaz1-Mar-09 2:59 
GeneralRe: It is Fantastic But I Have a problem Pinmemberma tju3-Mar-09 21:24 
GeneralRe: It is Fantastic But I Have a problem Pinmemberdanny gee9-Mar-09 18:52 
GeneralRecommendation Pinmemberdanny gee16-Feb-09 20:31 
QuestionWhen is the msgBox rendered? PinmemberChip Long4-Jan-09 15:25 
Questionerror message after clicking ok Pinmemberbytesighs31-Dec-08 3:15 
Questionshow error when i click Ok button? PinmemberMember 362888628-Sep-08 18:25 
AnswerRe: show error when i click Ok button? Pinmembertremie.soj7-Oct-08 23:28 
QuestionNão funciona com masterpage ? PinmemberKesley26-Sep-08 8:00 
GeneralShowing error when clicking ok PinmemberGeo Anto25-Aug-08 23:01 
Questionproblem using message box Pinmemberakssky11-Aug-08 8:44 
GeneralMsgBox for WindowsMobile PinmemberMember 29118465-Jun-08 3:40 
Generalits not working on update panel Pinmemberarunaxp15-May-08 21:34 
GeneralConfirm does not work PinmemberMS.NET13-Apr-08 3:55 
GeneralRe: Confirm does not work PinmemberTina P14-Oct-08 18:55 
Questionthe msgbox.dll is not working in VB.NET PinmemberRei Masi18-Feb-08 19:22 
Generalnot working in content page Pinmemberkidus128-Nov-07 6:05 
GeneralRe: not working in content page Pinmemberjcm123430-Mar-08 22:06 
GeneralRe: not working in content page PinmemberTankeeOner26-Oct-08 3:11 
GeneralTitle of the Message Box Pinmemberadin rivera5-Nov-07 9:46 
Generaltwo confirmation boxes wont work Pinmembersujith ms16-Oct-07 20:22 version please? PinmemberDonVBguy15-Oct-07 13:20 
GeneralDoes not work in 2.0 Pinmembervis200714-Aug-07 7:35 
GeneralRe: Does not work in 2.0 Pinmembervis200714-Aug-07 7:41 
GeneralRe: Does not work in 2.0 PinmemberJohn Read17-Sep-07 7:08 
GeneralRe: Does not work in 2.0 PinmemberNaved12345627-Jul-09 7:46 
Questionerror in vista premium home Pinmembermurathankocan10-Aug-07 0:55 
GeneralMy Cancel button isn't going back into pageload Pinmemberang00038-Aug-07 3:01 
GeneralRe: My Cancel button isn't going back into pageload Pinmemberjephyhl16-Oct-08 22:26 
GeneralOne important observation that only one pointed it out here Pinmemberbfawad2-Aug-07 12:34 
GeneralInvalid postback or callback argument Pinmemberbobscat24-Jul-07 5:09 
GeneralVery good article Pinmemberdelacru26-Jun-07 9:40 

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 | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 3 Sep 2004
Article Copyright 2004 by Ning Liao, Liang Yang
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid