Thursday, 10 November 2011

display an alert box using C#


As the C# language does not have an alert option, we can achieve it by including the below function and calling it where ever it is required.The code snippet is as follows,

public static class Alert
        {
            /// <summary>
            /// Shows a client-side JavaScript alert in the browser.
            /// </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 marks
                string cleanMessage = message.Replace("'", "\\'");
                string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

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

                // Checks if the handler is a Page and that the script isn't allready on the Page
                if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
                {
                    page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
                }
            }
        }


Example
if (age <= 18 || age >= 65)
{
Alert.Show("Employee's age must be between 18 and 65!");
}


The above function will display an alert in a blank page whereas if we want to display an alert in the same page, include the below snippet,

Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('ALERT MESSAGE');", true);


Example
if (age <= 18 || age >= 65)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('Employee's age must be between 18 and 65!');", true);
}



1 comment:

  1. Las Vegas Casino | Casino - DrMCD
    The 여주 출장마사지 best place to play, win, 서산 출장마사지 and gamble! Your favorite casino 구리 출장안마 slots and table games. · Try our FREE online slots 보령 출장안마 at MGM Grand, 구미 출장샵

    ReplyDelete