Validating textboxes in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xonel
    New Member
    • Mar 2012
    • 1

    Validating textboxes in C#

    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,numbe rs 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:
    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
  • rpk2006
    New Member
    • Sep 2006
    • 2

    #2
    For your first problem, disable "Allow Nulls" property in your database table (if using SQL Server).

    Comment

    Working...