Link to home
Start Free TrialLog in
Avatar of matthewsampson
matthewsampson

asked on

Counting Characters/words in a Text box

Hi Guys,

I am trying to produce a "real-time" count of characters or words in a text box as the user types.
I think counting the words will be too tricky but if there is a way of counting the characters in a label say (rather than another textbox), that would be great.
If possible real-time would be great, otherwise there could be a button?

Any help would be great.

Many Thanks
Avatar of toddhd
toddhd

dim Count() as string = split(myTextBox.String)
lblWordCount.Text = Ctype(UBound(Count),String)
Not sure if I wrote that 100%, but my idea is just to do a Split() on the value of the textbox, which would give you an array of values - one array item for each word in the textbox. Then you can simply send the length of the array to a label or whatever you like.
You could also use regluar expressions and a match count.
FWIW, many programs don't consider some words, such as "a", the", "and", "as", etc. to be "words" in a word count. Using the array method, you might want to loop through the array, and delete any instances of "common words".

Also, I forgot to mention that you should simply wrap the code above in the TextChanged event of the textbox.
ASKER CERTIFIED SOLUTION
Avatar of toddhd
toddhd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Could someone interpret this into C# please?

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim Count() As String = Split(TextBox1.Text)
        Label1.Text = "Count = " & UBound(Count).ToString
    End Sub
Private Void TextBox1_TextChanged(System.Object sender, System.EventArgs e) Handles TextBox1.TextChanged
{
        String Count() = Split(TextBox1.Text);
        Label1.Text = "Count = " + UBound(Count).ToString;
 }

I'm not really a C# coder, but it would be something similar to that....