title: Count words in Visual Basic
body: <p>I am trying to implement a programme that counts the words in a multiline textbox as you type. I can get it counting the words until I press the "enter" key and type a word. It does not recognise this. This is my code:</p>
  
  <pre><code>Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim str As String
    Dim i, l, words As Integer
    str = TextBox1.Text
  
    str = LTrim(str) 'removes blank spaces at the beginning of text
    str = RTrim(str) ' removes blank spaces at the end of text
    l = str.Length
    i = 0
    words = 0
    While (i &lt; l)
      If str(i) = " " Then
        words = words + 1
        i = i + 1
        While str(i) = " "  ' removes more than 1  blank space
          i = i + 1
        End While
      Else
        i = i + 1
      End If
  
    End While
  
    words = words + 1 ' adds the last word
  
    TextBox2.Text = ("" &amp; words)
  
  End Sub 
  </code></pre>