1

How to display error message (POP UP window) occurred in code using try & catch block in ASP.net4.0?

3 Answers 3

3

This is a C# version. Create a function that displays the popup in your page

<script type="text/javascript">
function displayPopup(message)
{
   //code to display popup here
}
</script>

call this method using script generated from codebehind

try
{
   //your code here
}
catch(Exception ex)
{
 string script = "<script type=\"text/javascript\"> displayPopup('"+ex.Message+"'); </script>";
 ClientScript.RegisterClientScriptBlock(this.GetType(), "myscript", script);
}

VB

Try
   'Your code here
Catch ex As Exception
    Dim script As String = "<script type=""text/javascript""> displayPopup('" & ex.Message & "'); </script>"
    ClientScript.RegisterClientScriptBlock(Me.[GetType](), "myscript", script)
End Try
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot do it directly

because

1) The error come on code behind is at server side error , when your page is not rendered. 2) Asp.Net works as a Disconnected model , thus it construct the page at server side first and then render. If we want to show popup that is client side (javascript), we can write event on server side to show popup when the page rendered and loaded on client side using javascript methods.

Thus you have to generate the script on error occuring on server side, and register it to client script , example

 string script = "<script type=\"text/javascript\"> window.alert('"+ex.Message+"'); </script>";
 ClientScript.RegisterClientScriptBlock(this.GetType(), "alertscript", script);

RegisterClientScriptBlock will write the script on page directly so that when it renders these script will be excuted and you can see the alert of error.

You can write custom javascript function and call that function in the script instead of alert to show custom Popup Window.

Comments

0

You can do it like this

catch (Exception ex)
    {
        string message = string.Format("Message: {0}\\n\\n", ex.Message);
        message += string.Format("StackTrace: {0}\\n\\n", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
        message += string.Format("Source: {0}\\n\\n", ex.Source.Replace(Environment.NewLine, string.Empty));
        message += string.Format("TargetSite: {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert(\"" + message + "\");", true);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.