Another way to do it would be to do a replace...
- Textbox1.Text = Textbox1.Text.Replace("'", "")
Now if you're loading this data from some where the above solution might be practical, but if you're just worried about user entered data there is a better way to do it (in my opinion).
In the KeyPress event of the textbox you can find out which key was pressed and then decide whether or not to allow that character to be entered in the textbox. Here is an example that would not allow the ' key to be pressed inside of TextBox1
- Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
-
'MsgBox(e.KeyCode.ToString())
-
If e.KeyCode = Keys.Oem7 Then
-
e.SuppressKeyPress = True
-
End If
-
End Sub
Now, normally if you type Keys. You'll get a list of all the keys -- where "a" would be Keys.A, however since ' is a special character I had to uncomment the first msgbox line to find out what the key code was. You can uncomment and you'll get a message box for every key you press telling you the correct Key.CODE information for pressed key. Here is another example with multiple keys supressed:
- Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
-
'MsgBox(e.KeyCode.ToString())
-
Select Case e.KeyCode
-
Case Keys.Oem7
-
e.SuppressKeyPress = True
-
Case Keys.Oemcomma
-
e.SuppressKeyPress = True
-
Case Keys.OemPeriod
-
e.SuppressKeyPress = True
-
Case Keys.V
-
If e.Control Then
-
'if control+v stop from pasting
-
e.SuppressKeyPress = True
-
End If
-
End Select
-
End Sub
-
Now keep in mind this solution is great if you're working with user input. Also take a look at the last Case statement in the second block of code. This will stop a user from pasting into the textbox - obviously since the user could paste data into the box without actually pressing the ' and our code stopping them we need to disable that. If you want to be able to paste, just run some String.Replace() functions (as shown above) in the TextChanged event to cover yourself.