Saturday, March 24, 2012

Maintaining input texts format

I have an asp:textbox, that's used to enter x amount of data.

If a user wishes to hit enter twice to leave two spaces, how would i maintain that format while passing it to a database, or a function to write it to an html page. (which im doing now).

Thanks.!I think you should maintain true newline characters in the database.

Then, when rendering the text, simply replace each newline character with an HTML <br /> tag.

If you're unsure that I mean, let me know language (VB.NET or C#) you use and I'll write a sample.
Thanks for your reply.

I am using vb.net
The following is a complete test page. I hope it helps.

<%@. Page Language="vb" ValidateRequest="false" %>
<script runat="server"
Sub SaveButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs )
SaveInDatabase( InputText.Text )
BindFromDatabase()
End Sub

Sub Page_Load( ByVal sender As System.Object, ByVal e As System.EventArgs )
If Page.IsPostBack Then
BindFromDatabase()
End If
End Sub

Sub SaveInDatabase( Text )
' Here you'd save the text in the database,without replacing Newline characters
Session( "PretendDatabase" ) = Text
End Sub

Sub BindFromDatabase()
' get the text from the database
Dim RetrievedText As String = CType( Session( "PretendDatabase" ), String )
' replace newline characters with <br />
Dim RetrievedTextAsHtml As String = RetrievedText.Replace( System.Environment.Newline, "<" & "br /" & ">" )
' bind to whatever HTML element you like
OutputText.Text = RetrievedTextAsHtml
End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>Please enter some text:</p>
<asp:Textbox id="InputText" textmode="multiline" width="500" height="100" runat="server" />
<p><asp:Button id="SaveButton" text="Save" onclick="SaveButton_Click" runat="server" /></p>
<hr />
<p>This is the HTML, where newline characters are replaced with <br /> tags:</p>
<asp:Textbox id="OutputText" textmode="multiline" width="500" height="100" runat="server" />
</form>
</body>
</html>

0 comments:

Post a Comment