Click here to Skip to main content
15,919,422 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello
i want validation code for textbox in vb.net2010
just i want to accept the character and no accepting for spacing
Posted
Updated 30-May-17 21:43pm
v2
Comments
Shahin Khorshidnia 2-May-12 12:04pm    
Please specify that your are working on a WinForm or ASP.Net? or ....?

By clicking on Improve question and Tag it.

There are a number of ways to do this.
1) You could handle the keydown / keypress events of the textbox.
2) You could use a masked / custom text box (example - VB.NET TextBox Validation Control[^]).
 
Share this answer
 
Comments
Maciej Los 2-May-12 10:05am    
Great answer! My 5!
Abhinav S 2-May-12 13:13pm    
Thank you.
Shahin Khorshidnia 2-May-12 12:06pm    
Good answer.
Abhinav S 2-May-12 13:13pm    
Thank you.
Try this:

C#
void CharacterValidation(object sender, KeyPressEventArgs e)
       {
           if ((e.KeyChar >= 65 && e.KeyChar <= 90) || (e.KeyChar >= 97 && e.KeyChar <= 122) || e.KeyChar == 32 || e.KeyChar == 8)
           {
               e.Handled = false;
           }
           else
           {
               e.Handled = true;
           }
       }


Here's another one:

VB
Public Class MainForm

    Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz"

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim theText As String = TextBox1.Text
        Dim Letter As String
        Dim SelectionIndex As Integer = TextBox1.SelectionStart
        Dim Change As Integer

        For x As Integer = 0 To TextBox1.Text.Length - 1
            Letter = TextBox1.Text.Substring(x, 1)
            If charactersAllowed.Contains(Letter) = False Then
                theText = theText.Replace(Letter, String.Empty)
                Change = 1
            End If
        Next

        TextBox1.Text = theText
        TextBox1.Select(SelectionIndex - Change, 0)
    End Sub

End Class
 
Share this answer
 
v2
Comments
Shahin Khorshidnia 2-May-12 12:12pm    
Or instead of charactersAllowed: If Letter.UpperCase() = Letter.LowerCase() Then... (My Vote of 4)
Prasad_Kulkarni 2-May-12 23:41pm    
Thank You Shahin
Abhinav S 2-May-12 13:14pm    
Correct. 5.
Prasad_Kulkarni 2-May-12 23:41pm    
Thank You Abhinav.
VB
Private Sub txtName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtItemCode.KeyPress
        If Asc(e.KeyChar) = Keys.Space Then
            MessageBox.Show("Space not acceptable")
            Exit Sub
        Else
            MessageBox.Show("GOOD")
        End If
    End Sub
 
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