How to limit characters per line in the multiline textbox in windows form application
I am doing some thing like this in KeyPress
Event of textbox but it will not go to new line goes on start of the row
if (txtNewNotes.Text.Length % 50 == 0) txtNewNotes.Text += Environment.NewLine;
The property that you are checking (txtNewNotes.Text
) is for all the text in the TextBox (All the text from all the lines combined).
What you will need to check is the txtNewNotes.Lines
property that returns a string[]
of each line that is contained inside your TextBox. Iterate through those strings and check their lengths.
Remember that with your current code, you are only adding a new line at the end of the TextBox.
You will need to handle the case where a user goes back to a line in the middle of the TextBox and starts editing a line there, making that specific line longer than your 50 character limit and causing an undesired amount of new lines at the end of the TextBox
To get always at the end of the line use following code:
if (txtNewNotes.Text.Length % 50 == 0 && textBox1.Text.Length >= 50)
{
txtNewNotes.Text += Environment.NewLine;
// This sets the caret to end
txtNewNotes.SelectionStart = txtNewNotes.Text.Length;
}
however this implementation still haves many flaws. For example if you change line manually, this solution wont notice it. You might want to use txtNewNotes.Lines to follow how many characters there are on a line.
To limit the text in textbox per row use
private void txtNewNotes_KeyDown(object sender, KeyPressEventArgs e)
{
if (txtNewNotes.Text.Length == 0) return;
if (e.KeyChar == '\r')
{
e.Handled = false;
return;
}
if (e.KeyChar == '\b')
{
e.Handled = false;
return;
}
int index = txtNewNotes.GetLineFromCharIndex(txtNewNotes.SelectionStart);
string temp = txtNewNotes.Lines[index];
if (temp.Length < 45) // character limit
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
One thing need to be handled when user copy and paste the text it is not apply character limit