New Line Character not Recognized in ASP .Net Text Box - asp.net

I want to display the data with new line in text box. I am saving the comment in DB and then displaying the data on the UI.
The below is the .aspx code :-
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server"
Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Here is my DB Comment :-
This is test Comment./r/n Please do some reply on this.
How its showing on UI :-
This is test Comment./r/n Please do some reply on this.
Then I updated DB Comment :-
This is test Comment.<br /> Please do some reply on this.
How its showing on UI :-
This is test Comment.<br /> Please do some reply on this.
What I can change in asp .net file or in DB so that the data displays with new line in text box.

There are a few things to mention here:
You are actually using wrong escape sequences, it should be \r\n (backslash instead of slash)
If you get this data from somewhere else (e.g. the database), it probably would be correctly escaped
Consider check the string while debugging to verify what's actually coming from your source
When you've verified the text, you can then replace the necessary characters by correct escape characters:
Assuming this is coming as text in a variable myText:
This is test Comment.\r\n Please do some reply on this.
then you can think of This is test Comment.\\r\\n Please do some reply on this.
and you can do the following:
comment.Text = myText.Replace("\\r\\n", "\n"); // replace text "\r\n" by a new line escape sequence

You can use Wrap Property which display ASP.Net TextBox with multiline property to automatically continues on next line when it reaches the end.
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server" Wrap="true" Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Additionally, you can add this line in your css class to make sure proper lines break at <br> and preserve white space.
word-wrap: break-word;

Related

How do you insert a newline character within the RegularExpressionValidator ErrorMessage Field?

Consider this code below:
<asp:RegularExpressionValidator
ID="MyTestId"
ValidationGroup="MyTestGroup"
ErrorMessage="You are a silly user. You entered the wrong format for this problem. Please try again. Using this format! ELRLDKX##Z"
ValidationExpression="some unrelated regex"
runat="server"
ControlToValidate="MyTestTextbox">
</asp:RegularExpressionValidator>
Is there a way to insert an escape character of some sort into the ErrorMessage string to ensure that Please try again. Using this format! ELRLDKX##Z is on another line? I have tried, \n with no luck.
The Validator is on a web page, so you can just add html code to the text, like a <br />
ErrorMessage="You are a silly user. You entered the wrong format for this problem.<br />Please try again. Using this format! ELRLDKX##Z"

RegularExpressionValidator to limit input length and allow empty strings

I'm really bad with regex and was looking at another question almost identical to this but can't get it to work as I need.
I was to use a RegularExpressionValidator that will allow any character up to 255 characters or nothing at all. I tried,
ValidateExpression="^.{255}$"
but it throws an unhanded exception when the textbox that I'm checking is empty.
I've also tried
ValidateExpression="^.{,255}$"
Thank you
Rodney
Did you try ^.{0,255}$? Not sure what exception you are getting though.
EDIT: Also, if struggling with .Net regex, Regex Hero tester is a great help. I know there are other sites, but this one is by far the best, if you ask me.
The proper expression is ^.{0,255}$.
^.{255}$ will only match if there is exactly 255 characters, while ^.{,255}$ will match the literal string "{,255}".
If there are still issues after trying that, can you tell us the exception?
If it throws an HttpRequestValidationException exception, you can use the members of the UnvalidatedRequestValues class.
Mind that "Validation succeeds if the input control is empty" (MSDN). You may add a RequiredFieldValidator field to ensure that the user does not leave a text box blank (if you use the RequiredFieldValidator control inside an UpdatePanel control, make sure that the validator control and the control it is associated with are in the same panel - MSDN):
<asp:textbox id="myTB"
runat="Server">
</asp:textbox>
// ... MAKE SURE YOU DO NOT USE TextMode="Number"!!!
<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="myTB"
ErrorMessage="Please enter a number.<br />"
Display="Dynamic"
runat="server"/>
And as for regex, ^.{255}$ means match any character (except newline) exactly 255 times between string start and end. I think it makes sense to allow ^[1-9][0-9]{0,254}$ (for values like '34', '104', etc.).

Replace(Environment.NewLine, "<br/>") is not working as expected when displaying text on a web page

I'm not sure why the following code is not working as intended:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Where litMessage is the name of the literal control and messageBody is the name of the string variable.
My intention is to output a string onto a web page and to replace the line breaks with a br tag so that it can be displayed on the page correctly. However, nothing is replaced. When viewing the page source, it looks like the line breaks still exist in the string. Similarly, when displaying the string via MsgBox, it displays normally as well. I have also tried wrapping the output with the pre tag and it displays the line breaks properly as well.
The string was originally entered by a user through the use of an asp:Textbox and saved into a MSSQL database. It's retrieved and displayed on another webpage using an asp:Literal control. The only thing that happens to the string before it is submitted is that it is trimmed (i.e. textbox.Text.Trim()).
Perhaps there is something I did not consider?
Edit #1: Due to time constraints, I've decided to just wrap the text with the pre tag. It's an acceptable work around as it preserves the line breaks. Unfortunately, it doesn't explain why the code didn't work in the first place. In the meantime, I'll just leave the question unanswered until I find a proper answer.
Edit #2: Solution found and answered below. UpdatePanel tag added to the question for future reference.
After revisiting this issue, I have found that updatepanels were causing the problem.
Doing some more testing, I looked into what the string contained using the following code:
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
All four statements returned false. This was tested on the string before sending to the database as well as on the string retrieved from the database.
From my point of view, there had to be something on the markup that was removing the line breaks. At first, I thought the Literal, Textbox, and Label controls did something funny to line breaks when retrieved in the code behind. This is not the case (and would be bizarre if Microsoft let this happen).
Combing through the code some more, I found that all these controls were inside an UpdatePanel. Remembering my previous negative experiences with UpdatePanels, I then thought that this might just be the culprit. I removed it and lo and behold, the line breaks did not go away in the code. The code I posted just above all returned true.
Both pages had the controls for submitting the text and displaying the text inside an UpdatePanel. I found that the line breaks disappeared when retrieving the text from the page. When displaying the text onto the page, the UpdatePanel does not alter the string in any way. The following code ended up working just fine:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Although I'm still not sure why line breaks were still displayed correctly when using the pre tag or even displaying the retrieved value using a javascript alert box.
It's hard to say from the code you've posted, but if you're passing the myString varaible itself to the page (and not the return value of the Replace function) you'll need to do -
myString = myString.Replace(Environment.NewLine, "<br/>")
before passing it to the page.
If you use an UPDATEPANEL the myText..Replace(Environment.NewLine, "<br/>") WILL NOT WORK. I found out the hard way (spent 2 hours already)
The solution (when using updatepanel) is to set a "PostBackTrigger" like this:
<asp:UpdatePanel runat="server" ID="pnlUpdate" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btnDoThatShitAlready" />
</Triggers>
Just found this while looking for a solution for replace not working with text in the literal control while it resides within a formview. The way I solved it was, in the databinding for the literal, to pass the text to a string, do the replace on the string then put the processed text back into the literal's text field.
Protected Sub MyLit_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim text1 As String
text1 = CType(myFormView.FindControl("MyLit"), Literal).Text
text1 = Replace(text1, Environment.NewLine, "<br />")
CType(myFormView.FindControl("MyLit"), Literal).Text = text1
End Sub
I hope this helps you, and anyone else who might visit this site for a solution.
Regarding the 4 tests above that failed (author: nullexception)...
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
I tried those tests and they failed for me as well. Then, I noticed there was no test for just vbLf, so I tested it. BINGO! That was it!
So, this works...
Label.Text = MultiLineTextBox.Text.Replace(ControlChars.Lf, "<br />")
I wasted my two hours finding what was actually wrong.
Well, solution is instead of Environment.NewLine, use ControlChars.Lf
You can remove updatepanel which will sort out the problem for future data. But if you already have some data, using ControlChars.Lf will help.
You can use it like this, because the System.NewLine returns a "\r\n" string
dim messageBody as string = "some text here";
litMessage.Text = messageBody.Replace("\r\n", "< br />");
litMessage.Text = messageBody.Replace("\\\\n","< br />").Replace(Environment.NewLine, "< br />")
It has worked for me. Hope this might work for you as well.
var str = "Text sample to replace carriage return + newline ("
+ (char)13 + (char)10
+ #") and
the Environment.NewLine and "
+ Environment.NewLine
+ " and the unix \n new line character.";
str.Replace("\r\n","<br />")
.Replace(Environment.NewLine, "<br />")
.Replace("\n", "<br />");
The output is
Text sample to replace carriage return + newline (<br />) and<br /> the Environment.NewLine and <br /> and the unix <br /> new line character.
To put the label text next line we can use the below mentioned solution.
<asp:Label ID="lblAppointmentLocation" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Location").ToString().Replace(Environment.NewLine, "<br/>").Replace("\n", "<br />") %>'></asp:Label>
What you are really looking for is:
#Html.Raw(#Regex.Replace(input_to_be_printed_correctly, #"\r\n?|\n", "<br />"))
I'm using this code and it works :
Instead of
.Replace(Environment.NewLine, "<br/>")
use
.Replace("\n", "<br />")
Hope to be useful.

How can I write raw XML to a Label in ASP.NET

I am getting a block of XML back from a web service. The client wants to see this raw XML in a label on the page. When I try this:
lblXmlReturned.Text = returnedXml;
only the text gets displayed, without any of the XML tags. I need to include everything that gets returned from the web service.
This is a trimmed down sample of the XML being returned:
<Result Matches="1">
<VehicleData>
<Make>Volkswagen</Make>
<UK_History>false</UK_History>
</VehicleData>
<ABI>
<ABI_Code></ABI_Code>
<Advisory_Insurance_Group></Advisory_Insurance_Group>
</ABI>
<Risk_Indicators>
<Change_In_Colour>false</Change_In_Colour>
</Risk_Indicators>
<Valuation>
<Value xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></Value>
</Valuation>
<NCAP>
<Pre_2009></Pre_2009>
</NCAP>
</Result>
What can I do to make this appear on the screen? I noticed that Stack Overflow does a pretty good job of putting the XML on the scren. I checked the source and it's using <pre> tags. Is this something that I have have to use?
It would be easier to use a <asp:Literal /> with it's Mode set to Encode than to deal with manually encoding Label's Text
<asp:Literal runat="server" ID="Literal1" Mode="Encode" />
You need to HtmlEncode the XML first (which escapes special characters like < and > ):
string encodedXml = HttpUtility.HtmlEncode(xml);
Label1.Text = encodedXml;
Surrounding it in PRE tags would help preserve formatting, so you could do:
string encodedXml = String.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(xml));
Label1.Text = encodedXml;
As Bala R mentions, you could just use a Literal control with Mode="Encode" as this automatically HtmlEncodes any string. However, this would also encode any PRE tags you added into the string, which you wouldn't want. You could also use white-space:pre in CSS which should do the same thing as the PRE tag, I think.

Line breaks are being lost when sending text to the Database

For some reason the line breakes from ASP.NET textboxes are not being stored in my database.
I am using Server.HtmlEncode(txtAbout.Text) to take the text from the textbox.
This part works and text is taken out with line breaks.
But when I trace the text, the line breaks are lost after this line:
db.AddInParameter(dbCommand, "About", DbType.String, about);
db.ExecuteNonQuery(dbCommand);
In the stored procedure the varable #about is ntext.
In the table the column about is ntext
I hope someone can help.
Could you trace what the value of "about" is before sending it off to the stored procedure?
I suspect what is happening is when you are outputting the stored result, you are assigning it to a label. Rather output it to a literal:
<asp:Literal runat="server" id="litAbout" />
Then once you have done that, then do the "placement". For example:
litAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.NewLine, "<br/>");
Also, that is where you want to encode the output. You almost always only do the final transformations prior to outputting the result; the thinking is that you don't want to lose that raw input.
Outputting to a label isn't the problem. The problem is outputting it to a label without doing the replace Justin mentioned.
I just tested this in VS2010 (.NET 3.5) and it worked.
<asp:Label runat="server" ID="lblAbout" />
lblAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.Newline, "<br />");
This solution will work the same as the literal.

Resources