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

ASP.Net C# MessageBox

By , 27 Apr 2008
 

Website With MessageBox Interface
img1.png

Introduction

In my last two articles titled "Creating A Custom Message Box", I described how to create a simple message box which could be used in desktop applications. In this article I will explain how to create a message box class in c# to use in web applications.

Background

Any web developer will tell you, if you want to display a message box to a user of a web application, you need to use the JavaScript alert() or the confirm() functions and these functions are great for displaying simple messages and getting responses. But they lack in many areas such as not being able to add different icons or buttons and visually they are not great to look at.

Solution

If you want a message box that looks good and you can add your own buttons as well as your own icons, then your only solution is to do it your self. But don't panic, its really not that difficult. By using a combination of JavaScript and CSS, you can create a message box which your users can response to.

Solution Explained


Page Dimmer
The first thing that you will need to do is make the page content unaccessible, by this I mean once your message box is displayed, your user will not be able to click on any navigations links on your page without acknowledging the message box. This is where the page dimmer comes in. The page dimmer is simply a div element with a fixed position. What this does is place a div element over your page content. If you were to set the background color of the div, then your page content will no longer be visible.

After placing the div on the page with a fixed position and assuming you have set a background color for the div, your page content will no longer be viewable, because they are placed behind the div as mentioned.

Rather than making the page go white or what ever color when the message box is shown, it would be nice if the background was semi transparent so that you can at least see the page content. If your not quite sure about what I mean by this, take a look at the screen shots above. Notice that the background is semi transparent and the page content is still viewable. This gives the impression that the page is dimmed. Thus the name Page Dimmer. Listing 1.1 below is a sample CSS code, which demonstrates how to make a div semi transparent with a fixed position. Note that the background of the page is set to black, with a transparency of 50, which is set as the opacity. If you test the code below, you will not get a sense that the div is partially transparent. It will just appear as though the page is grey. But bare with me, you will get the full effect when you get to turn the page dimmer on and off.

Listing 1.1
.page_dimmer 
{ 
position<span class="code-none">:fixed<span class="code-none">; 
height<span class="code-none">:100%<span class="code-none">; 
width<span class="code-none">:100%<span class="code-none">; 
top<span class="code-none">:0px<span class="code-none">; 
left<span class="code-none">:0px<span class="code-none">; 
background-color<span class="code-none">:#000000<span class="code-none">; 
filter<span class="code-none">:alpha(opacity=50)<span class="code-none">; 
-moz-opacity<span class="code-none">:.50<span class="code-none">; 
opacity<span class="code-none">:.50<span class="code-none">; 
z-index<span class="code-none">:50<span class="code-none">; 
<span class="code-none">} </span></span></


Message Box
After creating a page dimmer, it's time to create the actual message box. The message box will consist of the title, message and OK button. The inner message box structure needs to be placed in a div. So you can design the layout of the message box however you like. Once you have designed and coded the inner message box structure such as where the title, message and OK button will appear, you need to place the code inside a div. This div needs to be centered on the screen and also fixed. It needs to be fixed so that if your page has scrollbars and the user scrolls down, then the message box should still appear in the same place, but the rest of the page content, which is displaying behind the page dimmer div should scroll up or down.

To position the div in the center of the screen, I used the CSS top, left and right properties with a percentage, this is not really centering the div, it just gives the illusion that the div is centered horizontally. The code for the message box CSS is listed below in Listing 1.2.

Listing 1.2
.msg_box_container 
{ 
position<span class="code-none">:fixed<span class="code-none">; 
background-color<span class="code-none">:#888888<span class="code-none">; 
border<span class="code-none">:1px solid #999999<span class="code-none">; 
z-index<span class="code-none">:50<span class="code-none">; 
left<span class="code-none">:20%<span class="code-none">; 
right<span class="code-none">:20%<span class="code-none">; 
top<span class="code-none">:20%<span class="code-none">; 
<span class="code-none">} </span></span></

Putting It All Together
At this point I should mentioned that the message box div should not be nested within the page dimmer div. The reason for this is because the page dimmer is semi transparent and anything placed inside the page dimmer div will also appear transparent. Listing 1.3 below shows the complete CSS and HTML for the message box.

Listing 1.3
<style> 
.page_dimmer 
{ 
position:fixed; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
background-color:#000000; 
filter:alpha(opacity=50); 
-moz-opacity:.50; 
opacity:.50; 
z-index:50; 
} 


.msg_box_container 
{ 
position:fixed; 
background-color:#888888; 
border:1px solid #999999; 
z-index:50; 
left:20%; 
right:20%; 
top:20%;" 
} 

</style> 

<div class="page_dimmer" id="pagedimmer"> </div> 
<div class="msg_box_container" id="msgbox"> 
<table width="100%"> 
<tr> 
<td colspan="2">[TITLE]</td> 
</tr> 
<tr> 
<td>[ICON]</td> 
<td>[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2"><input type="Button" value="OK"></td> 
</tr> 
</table> 
</div> 

Save the above code and place some content just under the message box div.

The Code
Its now time to take a look at the scripting behind the OK button, which will be used to close the message box and remove the page dimmer. Before I present the JavaScript code, take a look at the code in listing 1.3 again. Take note, that both the page dimmer and message box div have an ID attribute. This is very important, as we will be using JavaScript DOM to get the div reference so that we can turn the visibility of the page dimmer and the message box div on and off. Listing 1.4 below show how to get a reference to the page dimmer and message box div (The Objects) by using the DOM getElementById() method.

Listing 1.4
document.getElementById('page_dimmer') 
document.getElementById('msgbox') 

The above code is fairly simple and doesn't actually do anything. The code below in listing 1.5 however shows how to set the visibility of each div to hidden.

Listing 1.5
document.getElementById('pagedimmer').style.visibility = 'hidden' 
document.getElementById('msgbox').style.visibility = 'hidden' 

Now that we have the code to set both divs to be hidden, its time to put all the code together, that is CSS, HTML and JavaScript. Listing 1.6 below is the complete code for the message box. You can save it and test the OK button.

Listing 1.6
<style> 
.page_dimmer 
{ 
position:fixed; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
background-color:#000000; 
filter:alpha(opacity=50); 
-moz-opacity:.50; 
opacity:.50; 
z-index:50; 
} 


.msg_box_container 
{ 
position:fixed; 
background-color:#888888; 
border:1px solid #999999; 
z-index:50; 
left:20%; 
right:20%; 
top:20%;" 
} 

</style> 

<div class="page_dimmer" id="pagedimmer"> </div> 
<div class="msg_box_container" id="msgbox"> 
<table width="100%"> 
<tr> 
<td colspan="2">[TITLE]</td> 
</tr> 
<tr> 
<td>[ICON]</td> 
<td>[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2"><input type="Button" value="OK" 
   onClick="document.getElementById('pagedimmer').style.visibility = 'hidden'; 
          document.getElementById('msgbox').style.visibility = 'hidden'"></td> 
</tr> 
</table> 
</div> 


Notice the OnClick event in the input tag?

ASP.Net C# Custom Message Box
It is now time to develop a reusable message box class. Now that we know how to set up a message box, we can easily begin to develop a custom C# class to do away with all the hassle of having to write the code every time we want to use it. At this point many of you might have some ideas of how to develop the class your self. But rather than shooting off to write the code, stick around and read a little more.

The approach I have taken to develop the message box class is quite simple. The class consists of six public methods one of which returns a string. They are as follows:

public void SetTitle(string msg_title) 
public void SetIcon(string msg_icon) 
public void SetMessage(string msg_message) 
public void SetOKButton(string msg_button_class) 
public void AddButton(string msg_button) 
public string ReturnObject() 

The SetTitle() method simply sets the title of the message box. The SetIcon() method sets the icon to be used for the message box. It takes a string as an argument which is the file path of the image to be used as an icon. The SetMessage() method sets the message body of the message box. The SetOKButton() actually should not be a method but rather coded in as part of the message box, this is because every message box needs a button to close it. Hover ever in order to show the OK button on the attached sample, you need to call this method. You can remove it and code the OK button in directly. This method takes one argument, which is the CSS class to apply styling to the button. Next is the AddButton() method. This method is responsible for adding additional buttons to the message box, which when clicked will navigate to other pages.

Before you can call the AddButton() method, you need to first create an instance of a MessageBoxButton Class. This class simply returns a HTML button code. You set the onClick event of the button, which is basically navigating to another page by using the SetLocation() method of the MessageBoxButton class. You then return the HTML code using the ReturnObject() method and set it as the argument for the AddButton() method. You can create as many instances of the MessageBoxButton class to keep adding buttons to the message box. All you need to do is keep using the AddButton() method, which stores all the html code for each button in an ArrayList. Finally the ReturnObject() method for the MessageBox class returns the HTML code for the message box, including the page dimmer. All CSS is inline.

Templating
Finally, rather than hard coding the structure of the message box code into the MessageBox class, I decided to create a template file, which consists of the page dimmer and message box HTML code along with inline CSS. The template file contains markers which is used to insert the title, icon, message body and buttons. This approach of using a template allows you to design your own message box layout, giving it the appearance you want. All you have to do is make sure the markers are in the template.

The Constructor of the MessageBox class takes one argument, which is the file path of the message box template. Listing 1.7 below shows the contents of the template file.

Listing 1.7
<div style="position:fixed;height:100%;width:100%;top:0px;left:0px;
    background-color:#000000;filter:alpha(opacity=55);-moz-opacity:.55;opacity:.55;z-index:50;" 
    id="pagedimmer"> </div> 
<div style="position:fixed;background-color:#888888; border:1px solid #999999; z-index:50; left:20%; 
    right:20%; top:20%;" id="msgbox"> 
<div style="margin:5px;"> 
<table width="100%" style="background-color:#FFFFFF; border:1px solid #999999;"> 
<tr> 
<td colspan="2" style="font-family:tahoma; font-size:11px; font-weight:bold; 
    padding-left:5px; background-image: url(msg_title_1.jpg); color:#FFFFFF; height:22px;">[TITLE]</td> 
</tr> 
<tr> 
<td style="width:100px; text-align:center;">[ICON]</td> 
<td style="font-family:tahoma; font-size:11px;padding-left:5px;">[MESSAGE]</td> 
</tr> 
<tr> 
<td colspan="2" style="border-top:1px solid #CCCCCC; padding-top:5px;text-align:right;">[BUTTONS]</td> 
</tr> 
</table> 
</div> 
</div> 

The markers are highlighted in bold. Notice also the CSS for both the page dimmer and message box div's are contained in style tags.

Finally Listing 1.8 and Listing 1.9 below is the code for the MessageBox and MessageBoxButton class.

Listing 1.8 - MessageBox Class
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;

public class MessageBox

{
    private string strLine;
    private StringBuilder msgbox;
    private StreamReader readtemplte;
    private string msgbox_title = "";
    private string msgbox_icon = "";
    private string msgbox_message = "";
    private string msgbox_ok_button = "";
    private string msgbox_buttons = "";
    private ArrayList msgbox_button;

    public MessageBox(string tpl_path)
    {
        readtemplte = new StreamReader(tpl_path);
        msgbox = new StringBuilder();
        msgbox_button = new ArrayList();

        while ((strLine = readtemplte.ReadLine()) != null)
        {
            msgbox.Append(strLine);
        }
    }

    public void SetTitle(string msg_title)
    {
        this.msgbox_title = msg_title;
    }

    public void SetIcon(string msg_icon)
    {
        this.msgbox_icon = "<img src=\"" + msg_icon + "\">";
    }

    public void SetMessage(string msg_message)
    {
        this.msgbox_message = msg_message;
    }

    public void SetOKButton(string msg_button_class)

    {
        this.msgbox_ok_button = "<input type=\"button\" value=\"OK\" class=\""
        + msg_button_class + 
        "\" onClick=\"document.getElementById('pagedimmer').style.visibility = 'hidden';" 
        + "document.getElementById('msgbox').style.visibility = 'hidden';\">";
    }

    public void AddButton(string msg_button)
    {
        msgbox_button.Add(msg_button);
    }

    public string ReturnObject()
    {
        int i=0;
        while (i < msgbox_button.Count)
        {
            msgbox_buttons += msgbox_button[i] + " ";
            i++;
        }

        msgbox.Replace("[TITLE]", this.msgbox_title);
        msgbox.Replace("[ICON]", this.msgbox_icon);
        msgbox.Replace("[MESSAGE]", this.msgbox_message);
        msgbox.Replace("[BUTTONS]", msgbox_buttons + this.msgbox_ok_button);

        return msgbox.ToString();
    }

}


Listing 1.9 - MessageBoxButton Class

using System;
using System.Text;
using System.Web;
using System.Web.UI;

public class MessageBoxButton
{
    private string msg_button = "";

    public MessageBoxButton(string btnValue)
    {
        msg_button = "<input type=\"button\" value=\"" + btnValue + "\"";
    }

    public void SetClass(string btnClass)
    {
        msg_button += " class=\"" + btnClass + "\"";
    }

    public void SetLocation(string btnLocation)
    {
        msg_button += " onClick=\"window.location='" + btnLocation + "'\"";
    }

    public string ReturnObject()
    {
       return msg_button += ">";
    }

}

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Syed M Hussain
Web Developer
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberKailash_Singh15 Jun '11 - 22:44 
fgdg
fgfdgdfg
fdgfdgdfgdfgfgg
GeneralMy vote of 5mvpSandeep Mewara19 Feb '11 - 18:11 
Nice one!
GeneralNice onememberkanchan.srajput26 Nov '10 - 0:04 
This is very funtastic code but some problem when i click on another button.
message box open again and again.
 
Rpl
Thanks in advance
GeneralDisplaying the messagebox without reloading the pagememberSoren-a25 Oct '10 - 2:10 
Hello
 
First of all - nice bit of code Smile | :)
 
I do have a question thou. Is it possible to display the messagebox without reloading the page? Like when I click on a button, then if a certain condition is met, the messagebox should be displayed.
 
My program is in C#.
 
Thanks in advance.
 
Regards
Søren Augustesen
GeneralRe: Displaying the messagebox without reloading the pagememberShama Shahzadi2 Jun '11 - 3:38 
its very simple....
if (result!=false)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Problem in Saving')", true);
}
GeneralRe: Displaying the messagebox without reloading the pagememberSyed M Hussain2 Jun '11 - 3:50 
You do not need the script manager for this. You can show/hide the div elements using standard javascript. The two div elements you need have the following id's pagedimmer and msgbox.
 
If you want to show/hide the msgbox without refreshing the page you can use the following example code.
 
function showMsgBox(){
document.getElementById("pagedimmer").style.display ='block';
document.getElementById("msgbox").style.display ='block';
}
 
function hideMsgBox(){
document.getElementById("pagedimmer").style.display ='none';
document.getElementById("msgbox").style.display ='none';
}
GeneralNamespace compliation error for MessageBoxButtonmembertrgalan23 Jul '09 - 8:38 
This complies and runs successfully on my local computer but I get the error when running from my Web site. Have I not added a namespace?
 
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
 
Compiler Error Message: CS0246: The type or namespace name 'MessageBoxButton' could not be found (are you missing a using directive or an assembly reference?)
 
Source Error:
 
Line 17: protected void Page_Load(object sender, EventArgs e)
Line 18: {
Line 19: MessageBoxButton btn1 = new MessageBoxButton("Google");
Line 20: btn1.SetLocation("http://www.google.com");
Line 21: btn1.SetClass("msg_button_class");
 
tr

GeneralXML Document cannot have multiple root level elementsmemberMarlin710 Jul '09 - 10:40 
The tpl file is blocking the build/debug with the message in the subject line. Any tips to get around that?
 
Marlin 7

QuestionIsPostBack issue?memberbelaqua8422 May '09 - 12:47 
Hi,
 
I love this article, it is exactly the sort of thing I was looking to do. I'm having a problem with implementation though. I want to use this in an online application, and on the final page I intend to ask the client if they're sure they want to submit. However, there are no actions on our submit button, within Page_Load we check to see if Page.IsPostBack, and if it is send the user info to the DB. I tried adding submit_Onclick, but I think the PostBack is run first and you get sent to the next page before you reach submit_Onclick. So I tried moving if (Page.IsPostBack) within submit_Onlick but understandably an error was thrown.
 
I am afraid that your nifty thing may just not work for me, but before I give up I was curious if you had any suggestions?
 
Thanks!
AnswerRe: IsPostBack issue?membersimpa27 Feb '10 - 23:42 
I have the same issue is there any solution???
I tryed with a session object but it is not really possible to use.
GeneralRe: IsPostBack issue?membersimpa2 Mar '10 - 23:34 
This can be done with creating a cookie:
 
HttpCookie cookie = Request.Cookies["msgbox"];
if (cookie != null)
{}else
{
HttpCookie newcookie = new HttpCookie("msgbox");
newcookie.Expires = DateTime.Now.AddHours(0.5);
Response.Cookies.Add(newcookie);

 
Messagebox code....
 
}
GeneralRe: IsPostBack issue?membersimpa3 Mar '10 - 10:45 
and add this:
 
public void SetOKButton(string msg_button_class)
{
this.msgbox_ok_button = "<input type=\"button\" value=\"OK\" class=\"" + msg_button_class + "\" önClick=\"window.location.href='Examples.aspx';document.getElementById('pagedimmer').style.visibility = 'hidden'; document.getElementById('msgbox').style.visibility = 'hidden';\">";
}
Questionin IE 6 its not working.memberMember 455152710 Feb '09 - 2:25 
Can have any updates for IE6?
QuestionButtons in pop up not workingmemberVLathi29 Jan '09 - 16:04 
HI,
 
The pop up works great but the buttons , that is, Google , MSN and OK don't do anything. How can we capture which button user has clicked ? Thanks.
AnswerRe: Buttons in pop up not workingmemberSyed M Hussain29 Jan '09 - 22:28 
Hi VLathi
 
Make sure you have javascript enabled on your browser. To find out which button was clicked, you will need to edit the onclick function to return the id of the button instead of navigating to a webpage.
 
To to this you will need to give each button an id, this can be done in the messageboxbutton class.
 
Hope that makes sense.
 

GeneralRe: Buttons in pop up not workingmemberVLathi30 Jan '09 - 3:51 
Hi,
 
Do you mean add id to this method in messagebox class and then do something to capture that ID in onClick ? Can you give more details please or help with 1 sample addition to the code. I have added the message box seccessfully but cannot use unless I can have these buttons work. Thanks.
public void SetOKButton(string msg_button_class)
{
this.msgbox_ok_button = "<input type=\"button\" value=\"OK\" class=\"" + msg_button_class + "\" onClick=\"document.getElementById('pagedimmer').style.visibility = 'hidden'; document.getElementById('msgbox').style.visibility = 'hidden';\">";
}
GeneralRe: Buttons in pop up not workingmemberSyed M Hussain30 Jan '09 - 6:51 
Hi
 
Modify the constructor to this.
 
public MessageBoxButton(string btnValue, btnId)
      {
            msg_button = "<input type=\"button\" value=\"" + btnValue + "\" onclick=\"ButtonClick('" + btnId + "')\" ";
      }
 
Now create a javascript function ButtonClick
 

function ButtonClick(btnid){
alert(btnid);
}
 

Let me know if this helps.
GeneralNot working in Internet Explorer 6.0memberbalajinadipilli12 May '08 - 19:50 
Hi.. Ur code is working fine in IE 7.0, but in IE 6.0 I have a problem. page dimmer is applied only at the top of the page. please help me out with it..
 
Thank U .. Balu
GeneralRe: Not working in Internet Explorer 6.0memberSyed M Hussain14 May '08 - 10:49 
Hi Balu
 
I dont have internet explorer 6 on my machine, but I will test it on a machine at work tommorrow.
 

GeneralRe: Not working in Internet Explorer 6.0memberGrace Garcia16 May '08 - 17:19 
Hi! I got the same problem. Only the top portion is affected by page_dimmer.
QuestionRe: Not working in Internet Explorer 6.0memberJeroenh20 Nov '08 - 22:35 
I have the problem here also in IE6. The message appeat at the top of the screen.
In FF3 it works good
 
Is there already an solution for this problem?
 
Thx
AnswerRe: Not working in Internet Explorer 6.0memberSyed M Hussain21 Nov '08 - 1:30 
Hi Jeroenh
 
Unfortunately IE6 does not understand the CSS Position:fixed property. Currently I have no fix for IE6, It works in IE7.
 

QuestionRe: Not working in Internet Explorer 6.0memberaueu8 Jan '09 - 6:13 
sorry, but i have error on messageBox.cs in line 23
"readtemplte = new StreamReader(tpl_path);"
why the file sending the app to folder c:/website2/msgbox.tpl to look for the "msgbox.tpl".
 
i didn't manage to solve that.
dy
AnswerRe: Not working in Internet Explorer 6.0memberSyed M Hussain8 Jan '09 - 6:40 
Hi aueu
 
For testing purposes I stored the template file in the C:\ drive. You will need to change it.
 

GeneralVersion that works with VS2005 and .NET v2.0memberJon Lea1 May '08 - 6:08 
I'm still running VS2005 and .NET v2.0 - do you have a version of msgBox that can run under this configuration?
 
Thanks.
 
Jon.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 27 Apr 2008
Article Copyright 2008 by Syed M Hussain
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid