Reputation: 33
I'm not sure what's wrong here, but i'm trying to count words in a richtext box, and display that with a label.
I put a richtextbox in a tab control so I can have a tabbed text box. Which seems to make this a lot harder then it should
also this isn't the whole program, I took the parts relating to the richtextbox and word counter
Any help is appreciated :)
public RichTab()
{
InitializeComponent();
TabPage tp = new TabPage("Document");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
WordCount();
}
public RichTextBox RTTB()
{
RichTextBox rtb = null;
TabPage tp = tabControl1.SelectedTab;
if (tp != null)
{
rtb = tp.Controls[0] as RichTextBox;
}
return rtb;
}
private void WordCount()
{
MatchCollection wordColl = Regex.Matches(RTTB().Text, @"[\W]+");
label2.Text = wordColl.Count.ToString();
}
Upvotes: 1
Views: 1183
Reputation: 81610
I would probably just wire up the TextChanged
event of the RichTextBox, and count the words there:
rtb.TextChanged += rtb_TextChanged;
Then count the words (using Giorgio Minardi's regex):
private void rtb_TextChanged(object sender, EventArgs e) {
label2.Text = Regex.Matches(((RichTextBox)sender).Text, @"[\S]+").Count.ToString();
}
Upvotes: 2
Reputation: 2775
What's the actual issue ? Here's a simple routine to count words:
[Test]
public void CountWords()
{
const string sample = "How you doing today ?";
MatchCollection collection = Regex.Matches(sample, @"[\S]+");
var numberOfWords = collection.Count;
//numberOfWords is 5
Assert.IsTrue(numberOfWords == 5);
}
Upvotes: 1