Feb 17, 2009

C#.NET, Changing the text on a page from a control

Wanting to set an error message on a page from a control in C#.NET was a difficult task--at least until I learned how to do it. Some of my failed attempts included trying to set the parent's label directly, to setting a Session var. The first fails as the label doesn't exist in that context. The second fails because the Parent page's code runs first, leaving an unanswered error flag (via Session var).

The solution:

//Code inside of a UserControl, appearing on a page that
//has "literalParentError" used for displaying errors
//to the user.

   //Code that might break...
   //Provide the below error to the user
   Literal literalError = (Literal)this.Parent.FindControl("literalParentError");
   literalError.Text = (string)GetGlobalResourceObject("GRO_File", "Err_AppBroke");

The above allows for the means of a UserControl (.ascx) changing text located on its parent's page (.aspx). I found a question post from erik little having difficulties that lead to the above solution.

Where is this useful?

I needed it for multiple forms that users would fill out. I had one page that displayed different UserControls based on an earlier user selection. If any errors occurred, I wanted them to be displayed consistently across the board. Rather than editing all of the forms' UserControls each time a UI change was requested, a single change on the parent page saves time.

A search function UserControl could use this method of error display to keep consistency across entire site sections, yet still use the same code.

No comments: