Search code examples
c#winformstextboxword-wrap

How to wrap output text from multiline textbox (web control) with a pre-configured width?


I have a problem with text wrapping in TextBox (System.Web.UI.WebControls).

I have a textbox with columns set to 65, text mode property set to MultiLine and wrap property set to true.

When I gather the message, which the user has typed in with txtMessage.Text as a string, the line breaks "\r\n" are only put in where it happens in the UI, and not after 65 chars.

Is this possible to solve, whiteout writing my own wrapping code?

Ex. code:

In some init method:

txtMessage.Columns  = 65;
txtMessage.TextMode = TextMode.MultiLine;
txtMessage.Wrap     = true;

... The user types in some text and Submit ....

In an extraction method:

string text = txtMessage.Text;
// ...
// Do something with the text ...

The text, as typed, is:

0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"

during extraction the string becomes:

"01234567890123456789012345678901234567890123456789012345678901234567890123456789\r\n01234567890123456789"

since the text window only fits 100 chars in one line.

But the column is set to 65, so the result should be:

"01234567890123456789012345678901234567890123456789012345678901234\r\n56789012345678901234567890123456789"


Solution

  • Winforms TextBox control doesn't support the functionality you require natively. But, there are two solutions for you.

    1. Remove all newline and line breaks. Then add line break and new line characters after every 65 (or whatever the length you'd like) characters just before saving the values to database.

    2. Inherit TextBox class and write your own User Control to override the Text property to represent the functionality in point one above. In this way you could reuse this control (But, not sure that's a concern)

    Hope this helped.