// Precondition: Focus shifting from one of the address combo boxes // sender is ComboBox // Postcondition: If no address selected, focus remains and error provider // highlights the field private void listBoxSelectAddress_Validating(object sender, CancelEventArgs e) { // Downcast to sender as ComboBox, so make sure you obey precondition! ListBox lstBo = sender as ListBox; // Cast sender as combo box bool valid = true; // bool for testing if (listBoxSelectAddress.SelectedIndex == -1) { e.Cancel = true; // Stops focus changing process // Will NOT proceed to Validated event valid = false; } else { lstBo = listBoxSelectAddress; } if (!valid) // error message if not valid { e.Cancel = true; // Stops focus changing process // Will NOT proceed to Validated event NoAddressError.SetError(listBoxSelectAddress, "You must select an address."); MessageBox.Show("You must select an address.", "Error"); } }
// Precondition: Validating of sender not cancelled, so data OK // sender is Control // Postcondition: Error provider cleared and focus allowed to change private void listBoxSelectAddress_Validated(object sender, EventArgs e) { // Downcast to sender as Control, so make sure you obey precondition! Control control = sender as Control; // Cast sender as Control // Should always be a Control NoAddressError.SetError(control, ""); }