HttpModule to auto trim textbox data RRS feed

  • Question

  • User1181216341 posted

    I want to create a http module to trim white space from text box entries

    given a form like below if the user enteres 'Joe ' into the first name textbox, I want to be able to retrieve the value 'Joe' (no white space) still using this.FirstNameTextBox.Text in the page code behind, my idea was to create a module that would run trim method on the value of the Request.Form entries that have a specific naming convention

    <asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox><br />
    <asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox><br />
    <asp:DropDownList ID="RoleDropDown" runat="server"></asp:DropDownList>
    // method in the module to strip request Form entries that contain Textbox in the name
    private void TrimTextBoxRequestValues(object sender, EventArgs e)
        HttpRequest request = ((HttpApplication)sender).Request;
        for(int i = 0; i < request.Form.Count; i++)
                request.Form[i] = DoTrim(request.Form[i]);
    private string DoTrim(string value)
        return value.Trim();
    private bool IsTextBoxControl(string formKey)
        if(formKey.ToUpper().IndexOf("TEXTBOX") > -1)
            return true;
        // else
        return false;
    The problem I am facing is that the above code will not compile 

    Property or indexer 'System.Collections.Specialized.NameValueCollection.this[int]' cannot be assigned to -- it is read only

    Makes sense the HttpRequest Form collection is read only;
    does anyone know if there is an alternative way to accomplish this?
    // want to avoid writing this
    u.FirstName = this.FirstNameTextBox.Text.Trim();
    // and use this
    u.FirstName = this.FirstNameTextBox.Text;
    Friday, January 19, 2007 8:20 PM

All replies

  • User-158764254 posted

    I think i'd just build a better Textbox control.  If you create your own textbox server control, you can override the default behavior.

    For example:

    Public Class TextBox
        Inherits System.Web.UI.WebControls.TextBox
        Public Overrides Property Text() As String
                Return MyBase.Text
            End Get
            Set(ByVal value As String)
                MyBase.Text = value.Trim 'Automatically trim the Text property as it gets assigned
            End Set
        End Property
    End Class


    Friday, January 19, 2007 8:59 PM