簡體   English   中英

在FormClosing方法中處理是/否/取消消息框中的取消按鈕

[英]Handling Cancel Button in Yes/No/Cancel Messagebox in FormClosing Method

我在表單的FormClosing方法中放了一個Yes / No / Cancel Messagebox 現在這是消息框文本: 你想保存數據嗎?

如果用戶點擊取消按鈕,我不是專業人員,也不知道如何處理? 確切地說,單擊取消按鈕的結果必須是表單保持打開狀態。
如何防止在FormClosing方法中關閉我的表單?

我寫到目前為止:;)

DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning);

//...
else if (dr == DialogResult.Cancel)
{
    ???
}

請幫我完成我的代碼!
謝謝

FormClosing有一個布爾參數,如果函數返回,如果設置為True,將取消關閉表單IIRC。

編輯:例如,

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    // Set e.Cancel to Boolean true to cancel closing the form
}

看到這里

實際上我認為你缺少事件處理程序,哦,即使沒有偶數處理程序,你也不能轉向它。 您必須使用這樣的事件處理程序添加事件。

private void myform_Closing(object sender, FormClosingEventArgs e) 
{
    DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning)

    if (dr == DialogResult.Cancel) 
    {
        e.Cancel = true;
        return;
    }
    else if (dr == DialogResult.Yes)
    {
        //TODO: Save
    }
}

//now add a default constructor 
public myform()  // here use your form name.
{
    this.FormClosing += new FormClosingEventHandler(myform_Closing); 
}

請原諒我,如果這段代碼中有一些錯誤的拼寫,因為我沒有在c#中寫它並在這里復制粘貼。 我剛剛在這里寫了它。 :)

您可以擁有以下內容:

if(dr == DialogResult.Cancel)
{
    e.Cancel = true;
}
else if(dr == DialogResult.Yes)
{
    //Save the data
}

如果您選擇是或否,上述代碼應僅關閉表單,並在您選擇是時保存數據。

你應該嘗試這個功能

public DialogResult msgClose(string msg)
{
     return MessageBox.Show(msg, "Close", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
}

並使用這樣的。

private void frm_FormClosing(object sender, FormClosingEventArgs e)
{
     if (conn.msgClose("Application close?") == DialogResult.No)
         e.Cancel = true;
     else
     {
         this.Close();
     }
}

你可以試試這個:

if (MessageBox.Show("Are you sure you want to quit?", "Attention!!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
{
   //this block will be executed only when Yes is selected
   MessageBox.Show("Data Deleted", "Done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
  //this block will be executed when No/Cancel is selected
  //the effect of selecting No/Cancel is same in MessageBox (particularly in this event)
}

如果需要,可以使用DialogResult類單擊“ No和“ Cancel按鈕

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM