I have a class that is a dialog box and OnOK is called (within the dialog class) when the user presses the OK button. I check to see if what they did was valid and if not I want to have the dialog box stay up so they can correct the changes. Right now it just falls through and the dialog box is done. Does anyone know if I can "cancel" out of the OK state and stay in the dialog box?
The default implementation of CDialog::OnOK calls CDialog::EndDialog, which closes the modal dialog. If the user input is not valid, you can omit the call to the base class implementation of CDialog::OnOK to cancel the action and stay in the dialog box.
It sounded like you were talking about MFC since you mentioned an OnOK method. There is no OnOK method on the Windows Forms Form class. Is this a method that you defined? Is it an event handler? How is it getting called and what is it doing?
Ok. I have a button click event handler called "button1_Click". "button1" is my "OK" button on my dialog box.
In there I check to see if the user is wanting to overwrite an existing "setup" file. If so, I bring up a MessageBox with Yes and Cancel buttons and ask them if they really want to overwrite. If they press Cancel on the MessageBox I want to stay in the dialog box to reselect another setup file name.
How is your form getting closed? Clicking the button should not automatically close the form. Are you calling the Close method somewhere in the event handler?
Another way that you could handle this is to add an event handler for the Form Closing event. Closing is a cancellable event and you can prevent the form from closing by setting the Cancel property of the event arguments of this event to true.
Through all of the suggestions I figured it out. In the Forms Designer I was setting the DialogResult property of the Ok button to be "OK". This is why it was automatically exiting. The default is None. I set it back to the default. In the event handler for both the Ok and Cancel buttons I programatically set the DialogResult and issued Close() if necessary. Thanks for the help from all, this dogged me once before in another instance and I really wanted to get this resolved.
Below is my code:
private void button1_Click(object sender, System.EventArgs e) { foreach( string setupname in SaveComboBox.Items ) { if( setupname == SaveName ) { string str = string.Format("Setup name: {0} exists! Overwrite?", SaveName); DialogResult res = MessageBox.Show(str, "Save UserSetups", MessageBoxButtons.YesNo); if( res == DialogResult.Yes ) { // Delete usersetup in collection first for overwrite process _UserSetupCollection.Remove(SaveName); break; } else return;
} }
this.DialogResult = DialogResult.OK;
this.Close();
}
/// /// This is the Cancel button event handler /// ///