vbCrLf in Multiline TextBox shows up only when .Trim() is called
I have an ASP TextBox with TextMode set to MultiLine. I'm having problems with preserving the vbCrLf characters when a user tries to put line breaks into the text. When a button on the page is pressed, I'm taking the text from the control, trimming it using String.Trim, and assigning that value to a String property on an object (which, in turn assigns it to a private internal String variable on the object). The object then takes the value from the private internal variable and throws it into the database using a stored procedure call (the SP parameter it is put into is an nvarchar(4000)).
ASPX Page:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Inline" UpdateMode="Conditional"
ChildrenA开发者_高级运维sTriggers="true">
<ContentTemplate>
<!-- some other controls and things -->
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtComments" Width="100%" Height="60px" CssClass="TDTextArea" Style="border: 0px;" MaxLength="2000" />
<!-- some other controls and things -->
</ContentTemplate>
</asp:UpdatePanel>
code behind:
ProjectRequest.StatusComments = txtComments.Text.Trim
object property:
Protected mStatusComments As String = String.Empty
Property StatusComments() As String
Get
Return mStatusComments.Trim
End Get
Set(ByVal Value As String)
mStatusComments = Value
End Set
End Property
stored proc call:
Common.RunSP(mDBConnStr, "ProjectStatusUpdate", _
Common.MP("@UID", SqlDbType.NVarChar, 40, mUID), _
Common.MP("@ProjID", SqlDbType.VarChar, 40, mID), _
Common.MP("@StatusID", SqlDbType.Int, 8, mStatusID), _
Common.MP("@Comments", SqlDbType.NVarChar, 4000, mStatusComments), _
Common.MP("@PCTComp", SqlDbType.Int, 4, 0), _
Common.MP("@Type", Common.TDSqlDbType.TinyInt, 1, EntryType))
Here's the strangest part. When I debug the code, if I type
"test
test"(without the quotes) into the comments text box, then click the save button and use the immediate window to view the variable values as I step through, here is what I get:
?txtComments.Text
"test test"
?txtComments.Text.Trim
"test
test"
?txtComments.Text(4)
"
"c
?txtComments.Text.Trim()(4)
"
"c
Anyone have a clue as to what's going on here?
There are two problems at bay here. First, the immediate window in VB is converting the non-printable character to a space so you cannot see it. In C#, it will show the character using its replacement escape code (e.g. \n
or \r\n
), but VB does not. Second, VB sees the break as a line-feed only (vbLf
) not a carriage-return+line-feed (vbCrLf
). Thus, if you do the following in break mode in the immediate window you will see what I mean (assuming you type test
, hit Enter, test
in the comments box):
?txtComments.Text.Substring(4,1) = vbLf
True
May be, you should use Environment.NewLine
constant to get replaced with the vbCrLf
精彩评论