Limit characters per line in the multiline textbox in windows form application

ぃ、小莉子 提交于 2019-12-14 03:14:26

问题


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;

回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/26847867/limit-characters-per-line-in-the-multiline-textbox-in-windows-form-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!