How to validate .NET dialog items when using automatic DialogResult?
Question
At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.
Is this possible?
Solution
From here
Double-click the Closing field, and implement it as follows:
private void Second_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
// When the user attempts to close the form, don't close it...
e.Cancel = (dropdown.selecteditemindex >= 0);
}
OTHER TIPS
Disable your OK button until the combobox is changed to a valid value.
If you want check for something, you allways need some code behind the designer. For your case, you can use a "Closing" event in the form, check what you need and if you want, set "e.Cancel = true;" - then form will not be closed.
What I have done for this is to not set the DialogResult on the OK button, but put some code behind the button.
private void OkButton_Clicked(object sender, EventArgs e)
{
this.DialogResult = ValueComboBox.SelectedIndex >= 0
? DialogResult.Ok
: DialogResult.None;
}
You can keep using the OK and Cancel button functionality of dialogs, and then put this code in the Clicked handler for the OK button:
private void OkButton_Clicked(object sender, EventArgs e)
{
if (!IsValid()) {
this.DialogResult = System.Windows.Forms.DialogResult.None;
}
}
In the code above, IsValid()
is a method you have to implement, that validates the input fields on the dialog.