Sam Chege

Sam Chege

  • NA
  • 45
  • 4.2k

Validating textboxes in C#

Mar 21 2012 5:01 AM
Hi
 
This code here below allows only numbers and one decimal point to be typed on a textbox.
It does not prevent you from:
1. Saving nulls in the database
2. From pasting any other character(words, asterisks,numbers etc) to the textbox.
What do i have to add to the code to prevent the two problems from occurring?? More so how to prevent nulls from being saved to the database
Here is my code:
private void txtBalance_TextChanged(object sender, EventArgs e)
{
txtBalance.KeyPress += new KeyPressEventHandler(numbercheck_KeyPress);
}

private void numbercheck_KeyPress(object sender, KeyPressEventArgs e)
{
  if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}  
//only allow one decimal point

if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}    
Please help me figure out
Thanks

Answers (1)