Extend web control with an extension method

When using Label and TextBox controls, we often have the need to reset the text value and/or hide the control during a post back. A common example is when using a Label control to display messages to the user. We only need to set the message once after a postback. We may then need to reset the content of that message and not display the control all together on subsequent postbacks.  

To avoid repeating the same lines of codes, we can extent the web controls by adding an extension method that would handle that for us.

public static class ogUIExtensions
       /// <summary>
       /// resets the text control properties and hide
       /// </summary>
       /// <param name="ctrl"></param>
       public static void ResetAndHide(this WebControl ctrl)
            ctrl.Visible = false;
            (ctrl as ITextControl).Text = string.Empty; 

This snippet extends the WebControl class by adding a method that basically sets the Visible property to false (hide) and sets the Text property of the control to an empty string. The WebControl class has not Text property, so we need to upcast to the ITextControl interface to have access to that property. Both Label and TextBox controls implement the ITextControl interface.

We can use this extension method in this way:

Label lbl = new Label();

I hope it helps.