2013-11-21 149 views
1

我在c#中使用Windows窗體,並且在不同窗體(我有2)應該關閉而不是如何以及何時關閉時遇到問題。這是非常煩人的,因爲我覺得我應該能夠修復它。但是,我們走了。如何處理窗體關閉事件

我有兩種形式,一種叫做ContactForm的另一種形式的MainForm。

的的MainForm:

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; 
     } 
    } 

這就是所謂的形式: OK按鈕。

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按鈕使用我希望它關閉,其中工程。當我按下取消按鈕,並沒有(在出現的框中),我希望窗體保持打開,輸入仍然完好無損。現在它不起作用。

任何想法?

/Martin

+0

如果你做得對,那麼當按鈕的Click事件開始運行時,DialogResult已經被設置。所以如果它被取消,那麼你必須將DialogResult設置回無。 –

+0

謝謝,它工作。我應該看到的! – Manin

回答

1

您的代碼沒問題。我認爲問題在於你的Cancel Button本身。通過這個我的意思是你可能附上(由設計師或代碼的某個地方)DialogResul.Cancel到你的按鈕btnCancel.DialogResul財產。要解決這個問題,只需將其設置爲DialogResult.None

如果我是對的,這就是關閉你的第二個表格。

請參閱MSDN瞭解更多信息。

+0

哦,你很好。設計表單時,我已將DialogResult設置爲取消。我做到了,因爲我的老師明確告訴過我。哦,他知道什麼:P再次感謝! – Manin