简体   繁体   English

检查用户是否按yes \\ no \\ cancel的代码是什么? (C#)

[英]what is the code for checking if the user press yes\no\cancel ? (c#)

i'm using messageBoxButton.YesNoCancel button, and i wanna know which button the user press 我正在使用messageBoxButton.YesNoCancel按钮,我想知道用户按下哪个按钮

how do i do it ? 我该怎么做 ?

this is the code: 这是代码:

 MessageBox.Show("this item is already in the system, do you want to add it anyway ?",
                 "Question",MessageBoxButtons.YesNoCancel);

thanks... 谢谢...

You can store the answers in a DialogResult object. 您可以将答案存储在DialogResult对象中。 Then you can analyze the answers like that: 然后,您可以像这样分析答案:

       DialogResult result = MessageBox.Show("this item is already in the system, do you want to add it anyway ?", "Question",MessageBoxButtons.YesNoCancel);

       if (result == DialogResult.Yes) {
           //your code here
       } else if (result == DialogResult.Cancel) {
           //your code here
       } else if (result == DialogResult.No) {
          // your code here
       }

From http://msdn.microsoft.com/en-us/library/0x49kd7z.aspx : http://msdn.microsoft.com/zh-cn/library/0x49kd7z.aspx

        result = MessageBox.Show(message, caption, buttons);
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            // Closes the parent form.
            this.Close();
        }
DialogResult dialogResult = MessageBox.Show("your question?", 
                      "window title", MessageBoxButtons.YesNo);
switch(dialogResult){
   case DialogResult.Yes: break;
   case DialogResult.No: break;
}

All possible dialog results: 所有可能的对话框结果:

  • DialogResult.Yes DialogResult。是
  • DialogResult.No 对话结果
  • DialogResult.Cancel DialogResult.Cancel
  • DialogResult.Abort DialogResult.Abort
  • DialogResult.Ignore DialogResult.Ignore
  • DialogResult.None DialogResult.None
  • DialogResult.Retry DialogResult.Retry
  • DialogResult.OK 对话框结果

And see the MessageBox MSDN entry. 并查看MessageBox MSDN条目。

The MessageBox.Show function returns a value of type DialogResult that indicates which button the user clicked. MessageBox.Show函数返回DialogResult类型的值,该值指示用户单击了哪个按钮。 By examining that return value, you can figure out which one they chose. 通过检查该返回值,您可以找出他们选择了哪个。

DialogResult result = MessageBox.Show("this item is already in the system, do you want to add it anyway ?", "Question",MessageBoxButtons.YesNoCancel);

if (result == DialogResult.Yes)
{
    // they clicked Yes
}
else if (result == DialogResult.No)
{
    // they clicked No
}
else
{
    // they clicked Cancel
}

Alternatively, you could use a switch statement, rather than if . 或者,您可以使用switch语句,而不是if

if (MessageBox.Show(message, caption, buttons) == System.Windows.Forms.DialogResult.Yes) // or No or Cancel
        {

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM