I really love Extension methods released in .NET 3. Here are two simple, but useful examples:
This method will add a default text to your textbox, the text will be removed when the user focus the textbox, and if if it’s emtpy onblur, the default text will be shown again.
public static void AddTextRemovedOnFocus(this System.Web.UI.WebControls.TextBox tb, string text) { bool isPostback = ((System.Web.UI.Page)System.Web.HttpContext.Current.CurrentHandler).IsPostBack; if (tb.TextMode != System.Web.UI.WebControls.TextBoxMode.Password && !isPostback) tb.Text = text; else tb.Attributes.Add("value", text); tb.Attributes.Add("onfocus", string.Format("javascript: if({0}.value == '{1}') {0}.value='';", tb.ClientID, text)); tb.Attributes.Add("onblur", string.Format("javascript: if({0}.value == '') {0}.value='{1}';", tb.ClientID, text)); }
Another small method is this, just check if the string is empty or has no value when trimmed.
public static bool IsNullOrTrimEmpty(this string s) { return (s == null || s.Trim().Length == 0); }
The first extension method will apperar as a method on TextBox-objects, and the second on string objects.
Feel free to submit some other nice extension methods. 🙂
Extensions makes things simple, especially EPiServer development. Even something as common as
[code]
public static PageData GetParent(this PageData pd)
{
return DataFactory.Instance.GetPage(pd.ParentLink);
}
[/code]
saves a lot of time.
Yes, I love it!
Another nice one is
public static PageData GetPageData(this PageReference pr)
{
return DataFactory.Instance.GetPage(pr);
}