60 likes | 138 Views
C# - FCL/Form & Control Validation. John Kelleher. Validating Controls. Ensure correct data is input Validating event Raised when control is asked to validate contents Programmer writes event handler If contents found to be invalid programmer can notify user
E N D
C# - FCL/Form & Control Validation John Kelleher
Validating Controls • Ensure correct data is input • Validating event • Raised when control is asked to validate contents • Programmer writes event handler • If contents found to be invalid programmer can notify user • If contents found to be valid, Validated event is raised and focus is passed to next control
Validating Event • Only raised… • if control has CausesValidation property set to true …and • when focus is passed to next control whose CausesValidation property set to true • Programmer write response: e.g. inform user of error
Validating Event (contd.) • Event handler is of type CancelEventHandler • this passes CancelEventArgs object • Event handler sets Cancel flag to true for the CancelEventArgs object if data is invalid • Focus does not pass to next control! • Event handler sets Cancel flag to false for the CancelEventArgs object if data is valid • Validated event is raised
Example private ErrorProvider errorProvider = new ErrorProvider(); … Private void textbox_Validating(object sender, CancelEventArgs e) { string errText = “”; if (textbox.Text.Length == 0) { e.Cancel = true; errText = “This field must not be empty”; } errorProvider.SetError(textbox, errText); }
Code explanation • Basic error messaging system • If control validation fails, focus remains with control • Send empty string to errorProvider to clear error message/status • Ensure CausesValidation property for Cancel button is set to false • This ensures that focus can pass to the button and the user may cancel the form