How to implement a MaxLength on RichTextBox
Environment
Product Version | 2021.3.914 |
Product | RadRichTextBox for WPF |
Description
In this article, you will find how to restrict the input size of RadRichTextBox so you can ensure that the content doesn't exceed a specific number of characters.
Solution
The described behavior can be achieved using the DocumentStatisticsInfo class. To obtain the current number of characters after modification, you would need to subscribe to the DocumentContentChanged event of RadRichTextBox. Once you get the current amount of characters in the document, you can compare it with the limit to find whether the content exceeds the allowed characters count. If so, invoke the Undo() method to cancel the last change.
private void RadRichTextBox_DocumentContentChanged(object sender, EventArgs e)
{
int charsCount = this.radRichTextBox.Document.GetStatisticsInfo().CharactersCount;
if (charsCount > 30)
{
this.radRichTextBox.Undo();
}
}