3

I am looking for a way to trim all user input in ASP.NET without calling Trim() on every string instance. I came across extending the DefaultModelBinder for MVC. Is there a way to do this in web forms? What options are available? As a less desirable option, is there a way to incorporate this into the set method of a class?

Community
  • 1
  • 1
drobison
  • 858
  • 1
  • 14
  • 23

3 Answers3

8

You could create a custom TextBox which always returns a trimmed version of the text:

public class CustomTextBox : TextBox
{
    public override string Text
    {
        get { return base.Text.Trim(); }
        set { base.Text = value; }
    }
}

Then just use this instead of the normal TextBox anywhere you need this behavior.

David
  • 208,112
  • 36
  • 198
  • 279
4

Here is the utility method to trim all TextBoxes in a page (or a parent control) recursively.

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

Usage

protected void Button1_Click(object sender, EventArgs e)
{
    TrimTextBoxesRecursive(Page);
}
Win
  • 61,100
  • 13
  • 102
  • 181
  • This was the perfect solution for my current need. Quick implementation and didn't require changing all of controls in my existing project. I had a large page so I just replaced the control parameter with the nested panel of the controls I needed trimmed. – drobison Sep 26 '13 at 17:55
1

You have to call this extension method from the appropriate parent, e.g. Page.TrimTextControls

public static void TrimTextControls(this Control parent, bool TrimLeading)
{
  foreach (TextBox txt in parent.GetAllControls().OfType<TextBox>())
  {
    if (TrimLeading)
    {
      txt.Text = txt.Text.Trim();
    }
    else
    {
      txt.Text = txt.Text.TrimEnd();
    }
  }
}
Gary Walker
  • 8,831
  • 3
  • 19
  • 41