Override Text Property to auto trim Textbox value

2019-08-12 17:53发布

问题:

I want to override the Text property of a textbox to set its value as auto trimmed. For that, I had to define the following class:

public class TextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get { return base.Text.Trim(); }

        //Automatically trim the Text property as it gets assigned
        set { base.Text = value.Trim(); }
    }
}

But the issue is that it's not working for TextBoxes defined in a design page (.aspx) and it only works for dynamically created Textboxes.

I need such code that returns a trimmed value for all TextBoxes whether it is added dynamically or statically.

How can I fix this?

回答1:

You should create a custom control and give it a different name.

[DefaultProperty("Text")]
[ToolboxData("<{0}:TrimmedTextBox runat=server></{0}:TrimmedTextBox>")]
public class TrimmedTextBox : TextBox
{
    [Category("Appearance")]
    public override string Text
    {
            get { return base.Text.Trim(); }
            //Automatically trim the Text property as it gets assigned
            set { base.Text = value.Trim(); }
    }
}

After this, open your AssemblyInfo.cs and add the following line at the bottom:

 //[assembly: TagPrefix("yournamespace", "aspCustom")]
 [assembly: TagPrefix("WebformsSandbox", "aspCustom")]
 //change "aspCustom" to the prefix of your choice!

After this your tool should be available at design-time:

To call your Custom element in markup code, either draw it from the toolbox into the code or write:

<aspCustom:TrimmedTextBox ID="TrimmedTextBox1" runat="server"></aspCustom:TrimmedTextBox>

//EDIT I have found another working solution here by p.campbell: Find all textbox control in a page

This avoids creating a custom element at all. What you do is define a helpermethod in your Extensions class:

public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
    foreach (Control item in collection)
    {
        yield return item;

        if (item.HasControls())
        {
            foreach (var subItem in item.Controls.FindAll())
            {
                yield return subItem;
            }
        }
    }
}

After you have done this, you can iterate over all your Textbox controls on your page and trim the text:

foreach (var t in this.Controls.FindAll().OfType<TextBox>())
{ 
    t.Text = t.Text.Trim();
}

You should be able to filter this even more by using Where(t => t.Id.Contains("someValue") or whatever you like.

What you deem better is up to you.