[c#] How to show MessageBox on asp.net?

if I need to show a MessageBox on my ASP.NET WebForm, how to do it?

I try: Messagebox.show("dd");

But it's not working.

This question is related to c# asp.net

The answer is


I took the code from the brilliant @KrisVanDerMast and made it wrapped up in a static method that can be called as many times as you want on the same page!

/// <summary>
/// Shows a basic MessageBox on the passed in page
/// </summary>
/// <param name="page">The Page object to show the message on</param>
/// <param name="message">The message to show</param>
/// <returns></returns>
public static ShowMessageBox(Page page, string message)
{
    Type cstype = page.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = page.ClientScript;

    // Find the first unregistered script number
    int ScriptNumber = 0;
    bool ScriptRegistered = false;
    do
    {
        ScriptNumber++;
        ScriptRegistered = cs.IsStartupScriptRegistered(cstype, "PopupScript" + ScriptNumber);
    } while (ScriptRegistered == true);

    //Execute the new script number that we found
    cs.RegisterStartupScript(cstype, "PopupScript" + ScriptNumber, "alert('" + message + "');", true);
}

One of the options is to use the Javascript.

Here is a quick reference where you can start from.

Javascript alert messages


It's true that Messagebox.show("dd"); is not a part of using System.Web;,

I felt the same situation for most of time. If you want to do this then do the following steps.

  • Right click on project in solution explorer
  • go for add reference, then choose .NET tab

  • And select, System.windows.forms (press 's' to find quickly)

u can get the namespace, now u can use Messagebox.show("dd");

But I recommend to go with javascript alert for this.


There is pretty concise and easy way:

Response.Write("<script>alert('Your text');</script>");

You could just simply write but you have to use JavaScript regardless.

Page.ClientScript.RegisterStartupScript(Page.GetType(), "Message Box", "<script language = 'javascript'>alert('dd')</script>");

Message box is only defaultly available for windows form application.If you want to use the message box resource the you would have to use 'using system.windows.forms' to enable the message box for web forms mode.


You may use MessageBox if you want but it is recommended to use alert (from JavaScript) instead.

If you want to use it you should write:

System.Windows.Forms.MessageBox.Show("Test");   

Note that you must specify the namespace.


Messagebox is for windows only. You have to use Javascript

Alert('dd');