/*--------------------------------------------------------------------------------- DATA VALIDATION PROJECT R. Kessler Created 12/26/06 For C# 2005 --------------------------------------------------------------------------------- //See lesson 4 Data Validation Project bool isLegalChar = false; //used to filter out keystrokes private void txtCustomer_Validating(object sender, CancelEventArgs e) { //---this fires before validated event. Use it with the ErrorProvider control. CausesValidation property // for a textbox must be set to true (default). // If the textbox is empty, I cancel the transaction and tell C# what they typed is not valid and this // prevents the Validated event from firing. If the validated event fires, C# will think the textbox has valid data. if (txtCustomer.Text.Trim().Length == 0) { errorProvider1.SetError(txtCustomer, "Please enter customer name."); e.Cancel = true; //this will cancel the Validated event which tells C# the data IS valid } else { errorProvider1.SetError(txtCustomer, ""); } } //_____________________________________________________________________________ //Use both the Keypress & KeyDown events to trap your keys. Keydown fires first!!! private void txtCustomer_KeyPress(object sender, KeyPressEventArgs e) { if (isLegalChar) e.Handled = false; else e.Handled = true; } private void txtCustomer_KeyDown(object sender, KeyEventArgs e) { isLegalChar = false; if ((e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z) | (e.KeyCode == Keys.Space | e.KeyCode == Keys.Back)) isLegalChar = true; else isLegalChar = false; } //_____________________________________________________________________________