2011-03-24 56 views

回答

55
  1. 您對MessageBox.Show需要調用傳遞MessageBoxButtons.YesNo得到/沒有按鈕,而不是在OK按鈕。

  2. 該呼叫(這將阻止執行,直到對話框返回)的結果進行比較,以DialogResult.Yes ....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
{ 
    // user clicked yes 
} 
else 
{ 
    // user clicked no 
} 
+1

@xxMUROxx請不要編輯重構代碼的答案。如果您覺得需要添加改進的其他內容,請發表評論或添加您自己的答案。 – 2015-05-11 13:15:50

6
if(DialogResult.OK==MessageBox.Show("Do you Agree with me???")) 
{ 
     //do stuff if yess 
} 
else 
{ 
     //do stuff if No 
} 
+1

非常感謝您親切的先生:) – 6TTW014 2011-03-24 03:08:36

+0

@ Kimmy25:如果您使用它,請接受答案。 – Lazlo 2011-03-24 03:12:33

+3

這不會像預期的那樣工作,因爲else中的句子不會隨時被調用。 – 2011-03-24 17:24:12

8

如果你真的希望是和否按鈕(並假設的WinForms):

void button_Click(object sender, EventArgs e) 
{ 
    var message = "Yes or No?"; 
    var title = "Hey!"; 
    var result = MessageBox.Show(
     message,     // the message to show 
     title,     // the title for the dialog box 
     MessageBoxButtons.YesNo, // show two buttons: Yes and No 
     MessageBoxIcon.Question); // show a question mark icon 

    // the following can be handled as if/else statements as well 
    switch (result) 
    { 
    case DialogResult.Yes: // Yes button pressed 
     MessageBox.Show("You pressed Yes!"); 
     break; 
    case DialogResult.No: // No button pressed 
     MessageBox.Show("You pressed No!"); 
     break; 
    default:     // Neither Yes nor No pressed (just in case) 
     MessageBox.Show("What did you press?"); 
     break; 
    } 
} 
0

檢查:

     if (
MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes) 
        { 
         //YES ---> Ok IM ALRIGHHT 
        } 
        else 
        { 
        //NO --->NO IM STUCK 
        } 

問候

2

爲.NET 4.5的正確答案的更新版本會。

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxImage.Question) 
    == MessageBoxResult.Yes) 
{ 
// If yes 
} 
else 
{ 
// If no 
} 

此外,如果您想要將按鈕綁定到視圖模型中的命令,可以使用以下命令。這與MvvmLite兼容:

public RelayCommand ShowPopUpCommand 
{ 
    get 
    { 
    return _showPopUpCommand ?? 
     (_showPopUpCommand = new RelayCommand(
     () => 
       { 
       // Put if statement here 
       } 
     })); 
    } 
} 
0

這種方式可以在MessageBox窗口中按'YES'或'NO'按鈕的同時檢查條件。

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo); 
      if (d == DialogResult.Yes) 
      { 
       //Contents 
      } 
      else if (d == DialogResult.No) 
      { 
       //Contents 
      } 
相關問題