1
Answer

Validating textboxes in C#

Ask a question
Sam Chege

Sam Chege

12y
1.6k
1
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)