Tuesday, February 7, 2017

MessageBox in Asp.Net

 This post shows how to create a message box using java script  in asp.net pages.In windows application Message Box plays a important role in displaying information to users.But in asp.net pages there is no predefined Message Box Control so we create a alert box using using java script and information to the users.

Html Tag:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AspTutor.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblName" runat="server" Text="Enter Text"></asp:Label>
        <asp:TextBox ID="txtMessage" runat="server"></asp:TextBox>
        <asp:button runat="server" text="Click"  OnClick="Unnamed_Click"/>
        <asp:button ID="btnException" runat="server" text="Exception"  OnClick="btnException_Click"/>
    </div>
    </form>
</body>
</html>

Code Behind:
protected void Unnamed_Click(object sender, EventArgs e)
        {
            MessageBox(txtMessage.Text);
        }

        //Message Box
        private void MessageBox(string Message)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script>");
            sb.Append("alert('");
            sb.Append(Message);
            sb.Append("')");
            sb.Append("</script>");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        }

        protected void btnException_Click(object sender, EventArgs e)
        {
            try
            {
                int j = 0;
                int i = 1 / j;

            }
            catch (Exception ex)
            {
                MessageBox("Exception:" + ex.Message);
            }
        }


Output:




Download Source Code



No comments:

Post a Comment