Dot NET
Dot NET

Reputation: 4897

How to remove whitespace from an asp:TextBox when using MaxLength property?

I've got an asp:TextBox which has a max length of 50, through the MaxLength property. The contents of this text box is written to a database.

The problem is that if the user does not fill in all 50 characters, the rest of the text box is filled with white space - thus also being saved into the database like so.

Is there any way to combat this?

Upvotes: 2

Views: 6079

Answers (3)

ChrisF
ChrisF

Reputation: 137148

I'm going to go out on a limb here and suggest that you've declared your text column as NCHAR(50) or CHAR(50) rather than NVARCHAR(50) or VARCHAR(50).

The former will write 50 characters to the table - padding out the input with spaces if necessary. The latter will write up to 50 characters to the table.

If you make this change then any new data will be written without trailing spaces, but any existing data will have to be cleaned up:

UPDATE table SET column = RTRIM(column) WHERE column LIKE '% '

Upvotes: 7

OnResolve
OnResolve

Reputation: 4032

txtTextbox.Text = txtTextbox.Text.Trim();

// call to stored procedure follows

Upvotes: 2

Adrian
Adrian

Reputation: 2923

When getting the value from the text box in the code behind use ".Trim()" on the string retrieved. This will remove all preceding and trailing whitespace from the string.

Upvotes: 0

Related Questions