Tag Archives: extension method

Extension Methods in .NET 3

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;
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. 🙂