Canceling AcceptButton functionality

Yarko

Newcomer
Joined
May 20, 2006
Messages
3
Hey guys,

I have built a form that I want to display from my main form with ShowDialog(). I also added an OK button to the form and set the form property AcceptButton to the OK button control. So, when I display my form and click the OK button, the dialog is closed, and the ShowDialog() method returns DialogResult.OK as expected.

Now, I want to add some code to the Click event of the OK button to verify that certain conditions are met. If those conditions are not met, I want to display a message, and I DON'T want the dialog to close. So, how can I, from the click event method of the OK button, cancel the closing of the dialog? Is this possible at all?

Thanks for any help.

Yarko
 
Well, it might be easier to answer your question if we see some code, but basically, if you need to do validation you can use the validation events. For example, if you want to make sure that a text box contains a number before the form is closed, you could handle the Validating event, like so...
Visual Basic:
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    Dim i As Integer
 
    'TryParse will return false if the number can't be parsed, i.e. is not a valid number
    If (Not Integer.TryParse(TextBox1.Text, i)) Then
        'If the number is invalid....
 
        'Set e.Cancel to signify this and keep focus on the textbox
        e.Cancel = True
        'Tell the user
        MessageBox.Show("Number is not a valid integer")
 
        'You could also use a component like ErrorProvider to let the user know 
        'that their input is invalid
    End If
End Sub
 
Thank you very much for the response!

I don't think that approach will work. I have two text boxes on the form that start blank and need to have data entered into them. So, validation on the text controls won't work since the user can just click OK without even touching them.

I was hoping I could put code in the OK button click event like this (pseudocode):

if (field1 is blank or field2 is blank) then
display error
CANCEL DIALOG CLOSE
end if
 
Well... you could actually paste the same exact code into the FormClosing event handler. Setting e.Cancel to true would prevent the form from closing and give you a chance to communicate the issue to the user.
 
BEAUTIFUL! WONDEFUL! PERFECT! THANK YOU!


Code:
private void FrmFolders_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
	if (DialogResult == DialogResult.OK
		&& (textBox1.Text.Length == 0 || textBox2.Text.Length == 0))
	{
		MessageBox.Show("Please enter values for Folder 1 and Folder 2.",
			"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
		e.Cancel = true;
	}
}
Where do I send the cookies?
 
Back
Top