I have a simple Winform example that demonstrates what happens.
There is a GroupBox with two RadioButtons. The two buttons share a validating event handler. Also on the form is a Button that does nothing. No events are connected. Finally there is a CheckBox that controls the state of a passing validation. Checked it passes and unchecked it fails.
When the program starts and the user clicks on either RadioButton the validating event does not fire. Then when I click on any control other than the current button the Validating Event fires. The NOP button gives me something to click besides the CheckBox.
In this test the CheckBox represents the status of passing the validation.
This will not work because once I uncheck the CheckBox and then click a radio button the focus is forever stuck. You can't get the focus to the CheckBox to change its state.
The reason is the Validating event is always called when the focus is leaving and not when the RadioButton is clicked. It sees that "valdating" fails and cancels the event.
This is obviously the wrong approach. What should I be doing to test at the time of the initial click? The Click event happens after the state has changed.
What event should I use so that I can test validation before changing the RadioButton state? Then I can leave the button and fix the issue before trying again.
This example is a simplified test that shows my dead end. My real world example is the two RadioButtons select one of two similar tables in a DataGridView. The two tables are related and I want them to be on the same TabPage. When the user selects the alternate table I want to do a validation/confirmation before switching away. If the confirmation fails I want to cancel the radio button.
// Validate is called when the radio button is clicked and when it leaves the box
using System.ComponentModel;
using System.Windows.Forms;
namespace ValidateRadioButton
{
public partial class Form1 : Form
{
int count;
public Form1()
{
InitializeComponent();
}
private void radiobutton_Validating(object sender, CancelEventArgs e)
{
if (sender is RadioButton) {
// If box not checked, cancel radioButton change
// This becomes a Hotel California test, once unchecked you
// can never leave the control
e.Cancel = !chkAllowChange.Checked;
}
count++;
//Display the number of times validating is called in the title bar
//Demonstrates when the event is called
Text = count.ToString();
}
}
}