Alert Box in ASP.Net (C# & VB.Net)

Mohammed Imtiyaz Feb 27, 2015


Alert Box in ASP.Net

This tutorial will explain you how to display Message Box / Alert Box in ASP.Net using C# and VB.Net

we will use here a class file (Alert.cs) that can be used in ASP.Net web pages where you want to display Message Box.

Class file (Alert.cs)

Create a new Class file under App_Code folder of your application.

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

/// <summary>
/// Summary description for Alert
/// </summary>
public class Alert
    public Alert()
        /// <summary>
        /// A JavaScript alert
        /// </summary>
        /// <param name="message">The message to appear in the alert.</param>
    public static void show(string message)
    	// Cleans the message to allow single quotation mark.
        string strCleanMessage = message.Replace("'", "\'");
        string script = "<script type='text/javascript'>alert('" + strCleanMessage + "');</script";       

		// Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;       

		// Check if the handler is a page and that the script is not already on the page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="VC" %>
<html xmlns="">
<head runat="server">
	<title>Alert Box in ASP.Net</title>
	<form id="form1" runat="server">
		<asp:Button ID="btnShowMessage" runat="server" Text="Show Message" onclick="btnShowMessage_Click" />


using System;

public partial class VC: System.Web.UI.Page
    protected void btnShowMessage_Click(object sender, EventArgs e) 
    {"Hello World");
Note: You can use Alert.cs file for multiple programming languages (C# and VB.Net)


Partial Class VB
    Inherits System.Web.UI.Page     
    Protected Sub btnShowMessage_Click(sender As Object, e As System.EventArgs) Handles btnShowMessage.Click       "Hello World")    
    End Sub
End Class