Vaccano Vaccano - 1 year ago 120
C# Question

Limit the max number of chars per line in a textbox

Say I have the following:

<TextBox TextWrapping="Wrap"

Is there a way I can limit the max number of chars per line to 60?

I have seen ways to do it via keydown events, but that does not seem to be foolproof (ie what about pasting in a long block of text).

Answer Source

Given that you're responding to keydown events I assume that you want to make sure that the string behind the TextBox adheres to the "60 chars per line" rule. If that's the case you should make an event that subscribes to the TextChanged event on the TextBox. There you can fix up the text and either truncate or break apart lines that are too long.

(edit) To solve the display portion you can do as Kafuka suggested: just make the box wide enough to hold 60 characters, and use a monospaced font if you want to be sure. If you've made sure the string is correct this should fall into line easily.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download