Login


An Error Message Control

By Jonathan Wood on 1/3/2011
Language: C#
Technology: ASP.NETWinForms
Platform: Windows
License: CPOL
Views: 18,278
Web Development » ASP.NET Controls » User Controls » An Error Message Control

ErrorMessage Text Project

Download Source Code Download Source Code

Introduction

With desktop applications, you can throw up a message box to alert the user any time an error is detected. However, web applications don't directly support message boxes. Instead, the page being served should be modified to include information about the error. Ideally, you can do this and still keep your page looking good.

I've seen a number of different approaches to this. I've seen label controls used, which had to be made visible or invisible in addition to setting the label's text. And other approaches that seemed less than ideal to me. So I decided to create a simple little user control, which I find myself using on every web application I build.

My ErrorMessage Control

Listing 1 shows my ErrorMessage control. This is a very simple control that can be very handy for displaying error messages on a web page.

This control has two properties: Tag and CssClass. Tag specifies the type of HTML tag that surrounds the error message. <p> is used by default, but you could change it to <div> or something else if needed. The CssClass property does just what the name implies. It specifies the CSS class used with the tag. This allows you to easily control formatting of the error message. The default CssClass value is "errmsg".

The control also include three overloads for a SetError() method. This method sets the current error using a string message, an Exception object, or both.

Listing 1: The ErrorMessage User Control

<%@ Control Language="C#" ClassName="ErrorMessage" %>

<script runat="server">

    protected string _text;

    public string Tag
    {
        set { ViewState["Tag"] = value; }
        get
        {
            string s = (string)ViewState["Tag"];
            return (s == null) ? "p" : s;
        }
    }

    public string CssClass
    {
        set { ViewState["CssClass"] = value; }
        get
        {
            string s = (string)ViewState["CssClass"];
            return (s == null) ? "errmsg" : s;
        }
    }

    /// <summary>
    /// Sets the error message.
    /// </summary>
    /// <param name="msg">Message to display</param>
    public void SetError(string msg)
    {
        _text = msg;
    }

    /// <summary>
    /// Sets the error message.
    /// </summary>
    /// <param name="ex">Exception object that describes the error</param>
    public void SetError(Exception ex)
    {
        SetError("An Error Occurred", ex);
    }

    /// <summary>
    /// Sets the error message.
    /// </summary>
    /// <param name="msg">A message to prefix the error message</param>
    /// <param name="ex">Exception object that describes the error</param>
    public void SetError(string msg, Exception ex)
    {
        _text = String.Format("{0} : {1}", msg, ex.Message);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(HtmlTextWriter writer)
    {
        if (!String.IsNullOrEmpty(_text))
        {
            writer.WriteBeginTag(Tag);
            writer.WriteAttribute("class", CssClass);
            writer.Write(HtmlTextWriter.TagRightChar);
            writer.Write(HttpUtility.HtmlEncode(_text));
            writer.WriteEndTag(Tag);
        }
    }

</script>

Using the Control

To use the control, simply place it near the top of a webform. If you do not call the SetError() method, then the control will not be visible on the page. However, if you call SetError() with information about an error, then the control will appear using the specified HTML tag and CSS class.

Listing 2 shows an example of how you might use the ErrorMessage control in your web application. The code simply catches an exception and passes the information along to the ErrorMessage control. This causes the control to render onto the page.

Listing 2: Using the ErrorMessage Control

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        // Raise an "Object reference not set to an instance of an object" exception
        string s = null;
        char c = s[0];
    }
    catch (Exception ex)
    {
        ErrorMessage1.SetError("There was an error initializing the page", ex);
    }
}

Conclusion

That's about it. Again, a very simple control. But one I find myself using all the time.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.