Click here to Skip to main content
15,905,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 18:37pm

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.
 
Share this answer
 
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
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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900