views:

1525

answers:

2

I have the following webform:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="TestWebApp.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtMultiLine" runat="server" 
            Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="btnSubmit" runat="server" 
            Text="Do A Postback" OnClick="btnSubmitClick" />
    </div>
    </form>
</body>
</html>

and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior?

I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first.

+1  A: 

I ended up doing the following in the btnSubmitClick()

public void btnSubmitClick(object sender, EventArgs e)
{
    if (this.txtMultiLine.Text.StartsWith("\r\n"))
    {
        this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
    }
}

I must be really tired or sick or something.

Jared
+1  A: 

I think that the problem here is in the way that the browser renders the textarea contents, not with ASP.NET per se. Doing this:

public void btnSubmitClick(object sender, EventArgs e) {
  this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}

will let you reach the desired screen output, but you'll add an extra newline to the Text that the user didn't enter.

The ideal solution would be for the TextBox control in ASP.NET to always write the newline AFTER writing the open tag and BEFORE writing the contents of Text. This way, you'd reach the desired effect without trumping the contents of the textbox.

We could inherit from TextBox and fix this by overriding RenderBeginTag:

public override void RenderBeginTag(HtmlTextWriter writer) {
  base.RenderBeginTag(writer);
  if (this.TextMode == TextBoxMode.MultiLine) {
    writer.Write("\r\n"); // or Environment.NewLine
  }
}

Now, creating a new class for this small issue seems really overkill, so your pragmatic approach is completely acceptable. But, I'd change it to run in the PreRender event of the page, which is very late in the page lifecycle and would not interfere with the processing of the submitted text in the OnSubmit event of the button:

protected void Page_Load(object sender, EventArgs e) {
  this.PreRender += Page_OnPreRender;
}
protected void Page_OnPreRender(object sender, EventArgs e) {
  this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}