C# 如何处理表单关闭事件

C# 如何处理表单关闭事件,c#,winforms,windows-forms-designer,C#,Winforms,Windows Forms Designer,我在c#中使用Windows窗体,在不同窗体(我有2个)如何以及何时关闭和不关闭方面存在问题。这是非常恼人的,因为我觉得我应该能够修复它。但我们走了 我有两个表单,一个主表单调用另一个表单ContactForm 主要形式: private void btnAdd_Click(object sender, EventArgs e) { ContactForm frmContact = new ContactForm(); int index = lstCus

我在c#中使用Windows窗体,在不同窗体(我有2个)如何以及何时关闭和不关闭方面存在问题。这是非常恼人的,因为我觉得我应该能够修复它。但我们走了

我有两个表单,一个主表单调用另一个表单ContactForm

主要形式:

private void btnAdd_Click(object sender, EventArgs e)
    {
        ContactForm frmContact = new ContactForm();
        int index = lstCustomers.SelectedIndex;
        //If a customer is selected, export data for the selected customer to ContactForm
        if (index != -1)
        {
            frmContact.ContactData = customerMngr.GetCustomer(index).ContactData;
        }

        if (frmContact.ShowDialog() == DialogResult.OK) //Show the ContactForm object
        {
            //The user has chosen the OK button - add the new customer object
            customerMngr.AddCustomer(frmContact.ContactData);   //??      
            UpdateCustomerList();
        }

        if (frmContact.ShowDialog() == DialogResult.Cancel)
        {
            return;
        }
    }
这种形式被称为: 确定按钮

private void btnOK_Click(object sender, EventArgs e)
    {
        if (ValidateInput())
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
取消按钮:

private void btnCancel_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Do you want to cancel and discard all data?", "Cancel input", MessageBoxButtons.YesNo,
                MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
当使用ContactForm中的OK按钮时,我希望它关闭,这是有效的。当我按下cancel按钮和no(在出现的框中)时,我希望表单保持打开状态,输入保持不变。现在它不起作用了

有什么想法吗


/马丁

你的代码没问题。我认为问题在于你的
取消按钮本身。我的意思是,您可能(通过设计器或代码中的某个地方)将
dialogresl.Cancel
附加到按钮
btnCancel.dialogresl
属性。要解决此问题,只需将其设置为
DialogResult.None

如果我是对的,这就是结束你的第二张表格的原因


有关更多信息,请参阅

您的代码正常。我认为问题在于你的
取消按钮本身。我的意思是,您可能(通过设计器或代码中的某个地方)将
dialogresl.Cancel
附加到按钮
btnCancel.dialogresl
属性。要解决此问题,只需将其设置为
DialogResult.None

如果我是对的,这就是结束你的第二张表格的原因


有关更多信息,请参阅

如果操作正确,则当按钮的Click事件开始运行时,DialogResult已设置。因此,如果它被取消,那么您必须将DialogResult设置回None。谢谢,它成功了。我应该看到的!如果操作正确,则当按钮的Click事件开始运行时,DialogResult已设置。因此,如果它被取消,那么您必须将DialogResult设置回None。谢谢,它成功了。我应该看到的!哦,你很好。在设计表单时,我已将DialogResult设置为取消。我这样做是因为我的老师明确告诉我要这样做。哦,好吧,他知道些什么:再次感谢你!哦,你很好。在设计表单时,我已将DialogResult设置为取消。我这样做是因为我的老师明确告诉我要这样做。哦,好吧,他知道些什么:再次感谢你!