Search code examples
c#eventsrichtextboxtextchanged

Richtext Box-TextChanged Even and checking spaces in current line


Is that possible to check the no. of spaces in current line of the richtextbox with its text changes event... for example

lin1: word1 word2 word3
lin2: word1 word2 word3 word4

when i type space after word3 it shows me message that you cannot enter word4

Solution

  • First off, use this TextBox extension and apply it to your RichTextBox(see code below, complete version findable here)

    public class TextBoxExtension : TextBox
    {
     public TextBoxExtension (){ }
    
     public int CurrentLineIndex
     {
        get { return this.GetLineFromCharIndex(this.SelectionStart) + 1; }
     }
    }
    

    Then do the following:

    int maxWordsAllowed = 4;
    
    private void textChangedEventHandler(object sender, TextChangedEventArgs args)
    {    
        //This get the space character count in your current line 
        if (myRichTextBox.Lines[myRichTextBox.CurrentLineIndex].Split(' ').Length - 1) > maxWordsAllowed )
          MessageBox.Show("Reached Maximum Words for that line");    
    }