Click here to Skip to main content
14,449,862 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am trying to type a sentence in a text box in vb.net. while typing if I put multiple spaces between words it accepts. how do I restrict multiple spaces between words in vb.net?

What I have tried:

Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If (e.KeyCode = Keys.Space) And ((e.KeyCode + 1) <> Keys.Space) Then
e.SuppressKeyPress = True
Else

End If
End Sub
Posted
Updated 9-Feb-20 19:37pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Why on earth are you checking (e.KeyCode + 1)?

To do this, you have to keep track of the last key pressed. Then, in the KeyDown event, you check to see if the last key pressed is a space and the current key pressed is a space. If they are both true, then you set the e.Handled and e.SuppressKeyPress properties to true.

Now, if the current key pressed is not a space, put that key in the tracking variable.
   
Comments
CodeMine 10-Feb-20 0:39am
   
thank u for your solution
here is the code i did

Public Class Form1
Dim pk As Integer
Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Space And e.KeyCode = pk Then
e.SuppressKeyPress = True
End If
End Sub
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
pk = e.KeyCode
End Sub
End Class
Rate this:
Please Sign up or sign in to vote.

Solution 2

Public Class Form1
    Dim pk As Integer
    Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Space And e.KeyCode = pk Then
            e.SuppressKeyPress = True
        End If
    End Sub
    Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
        pk = e.KeyCode
    End Sub
End Class
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100