Alert Box in Asp.net (C# & Vb.net)

Feb 27, 2015 By Mohammed Imtiyaz

Download

Demo

Demo

Introduction

This tutorial will explain you how to display Message Box / Alert Box in Asp.net using C# and Vb.net

In this tutorial, we’ll use 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);

        }

    }

}

Aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="VC" %>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Alert Box in Asp.net</title>

</head>

<body>

    <form id="form1" runat="server">

    <asp:Button ID="btnShowMessage" runat="server" Text="Show Message"

        onclick="btnShowMessage_Click" />

    </form>

</body>

</html>

C#

using System;

public partial class VC : System.Web.UI.Page

{
    protected void btnShowMessage_Click(object sender, EventArgs e)
    {
        Alert.show("Hello World");
    }
}

NOTE: You can use Alert.cs file for multiple programming languages (C# and Vb.net)

VB.Net

Partial Class VB

    Inherits System.Web.UI.Page    
    Protected
Sub btnShowMessage_Click(sender As Object, e As System.EventArgs) Handles btnShowMessage.Click

       
        Alert
.show("Hello World")

   
    End
Sub
End Class



Post your comment