validations in textbox in vb.net(its allow only no's

VB
Private Sub TextBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
If Not IsNumeric(TextBox1.Text) Then
MessageBox.Show("You must enter a numeric value!", _
"Please try again....", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
Me.Focus()
End If
End Sub


Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If Not ((Convert.ToInt32(e.KeyChar) >= 48 AndAlso Convert.ToInt32(e.KeyChar) <= 57) OrElse Convert.ToInt32(e.KeyChar) = 46 OrElse e.KeyChar = Convert.ToChar(Keys.Space) OrElse e.KeyChar = Convert.ToChar(Keys.Back)) Then
e.Handled = True
End If


End Sub


C#
private void textBox2_Leave(object sender, EventArgs e)
{
String s = textBox2.Text;
Int32 result = 0;

Int32.TryParse(s, out result);

// result will equal zero if the parse failed.

if (result == 0)
MessageBox.Show("Invalid Value");
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
int keyAscii = (int)e.KeyChar;

if ((keyAscii >= 48 && keyAscii <= 57) || e.KeyChar == Convert.ToChar(Keys.Back))
{

e.Handled =
false;

}

else
{

e.Handled =
true;

}
OR

if (!((Convert.ToInt32(e.KeyChar) >= 48 && Convert.ToInt32(e.KeyChar) <= 57) || Convert.ToInt32(e.KeyChar) == 46 || e.KeyChar == Convert.ToChar(Keys.Space) || e.KeyChar == Convert.ToChar(Keys.Back)))
{
e.Handled = true;
}

}

No comments:

Post a Comment