Tony
Tony

Reputation: 12695

How to create custom TextBox control?

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 ?

Upvotes: 1

Views: 2628

Answers (3)

Mujahid Daud Khan
Mujahid Daud Khan

Reputation: 2071

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

Upvotes: 0

Thiago Vinicius
Thiago Vinicius

Reputation: 180

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();
            }
        }
    }
}

Upvotes: 3

Afnan Ahmad
Afnan Ahmad

Reputation: 2542

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);
}

Upvotes: 0

Related Questions