简体   繁体   English

使用 MaxLength 属性时如何从 asp:TextBox 中删除空格?

[英]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.我有一个 asp:TextBox,它的最大长度为 50,通过 MaxLength 属性。 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.问题是,如果用户没有填写所有 50 个字符,文本框的其余部分将填充空白 - 因此也会像这样保存到数据库中。

Is there any way to combat this?有什么办法可以对抗这种情况吗?

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) .我将在这里大胆地建议您将文本列声明为NCHAR(50)CHAR(50)而不是NVARCHAR(50)VARCHAR(50)

The former will write 50 characters to the table - padding out the input with spaces if necessary.前者将向表中写入 50 个字符 - 如有必要,用空格填充输入。 The latter will write up to 50 characters to the table.后者将最多向表中写入 50 个字符。

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 '% '
txtTextbox.Text = txtTextbox.Text.Trim();

// call to stored procedure follows

When getting the value from the text box in the code behind use ".Trim()" on the string retrieved.当从后面的代码中的文本框中获取值时,在检索到的字符串上使用“.Trim()”。 This will remove all preceding and trailing whitespace from the string.这将从字符串中删除所有前面和后面的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM