1

I want to perform Trim() method on each TexBox control on my page, before value is returned. I dont' want to hard-code the same code for each TexBox control, I want to do it in more elegant way.

I've found made the following class

namespace System.Web.UI.WebControls
{
    public partial class TrimmedTextBuox : TextBox
    {
        private string text;
        public override string Text
        {
            get { return string.IsNullOrEmpty(text) ? text : text.Trim(); }
            set { text = value; }
        }     
    }
}

but it fails, while debuggind the compiler doesn't get inside get{} and set{}.

After that, I created a UserControl item, but it must be deriverd from System.Web.UI.UserControl, not System.Web.UI.WebControls.TextBox to get it work (there's an exception which points to that)

So, how can I do that ?

ekad
  • 14,436
  • 26
  • 44
  • 46
Tony
  • 12,405
  • 36
  • 126
  • 226

3 Answers3

3

First you have to register your control in your .aspx page like that:

<%@ Register TagPrefix="customControls" Namespace="WebApplication.Custom.Controls" Assembly="WebApplication"%>

Then you can call it using the markup

<customControls:TrimmedTextBuox  ID="txtTrim" runat="server"/>

Plus you don't have to create another "text" property in your custom TextBox. Instead, it can be done like that:

namespace WebApplication.Custom.Controls
{
    public class TrimmedTextBuox : TextBox
    {
        public override string Text
        {
            get
            {                
                return base.Text;
            }
            set
            {
                if (!String.IsNullOrEmpty(value))
                    base.Text = value.Trim();
            }
        }
    }
}
Thiago Vinicius
  • 170
  • 1
  • 10
0

This will trim recursively all text boxes before inserting.

 public static void trimRecursive(Control root)
    {
      foreach (Control control in root.Controls)
      {
        if (control is TextBox)
        {
            var textbox = control as TextBox;
            textbox.Text = textbox.Text.Trim();
        }
        else
        {
            trimRecursive(control);
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    trimRecursive(Page);
}
Afnan Ahmad
  • 2,492
  • 4
  • 24
  • 44
0

Simple Solution to your problem is to hide the Text property of your base class by using new keyword. sample code...

public class TrimmedTextBox : TextBox
{
    public new string Text
    {
        get
        {
             var t = (string) GetValue(TextProperty);
            return t != null ? t.Trim() : string.Empty;
        }
    }
}

For more info about how new keyword with property works refrer to this SO Question

Community
  • 1
  • 1
Mujahid Daud Khan
  • 1,983
  • 1
  • 14
  • 23