How do I detect a button that is default and cancel


  • Hello

    How do I detect a button that is default and cancel. I have used the following code

    MessageBox.Show(" The default and cancel buttons are => " + this.AcceptButton.ToString() + " and => " + this.CancelButton.ToString());

    Manoj Gokhale

    Wednesday, April 12, 2017 12:06 PM

All replies

  • where are you using messgebox? Is it like you want to detect which button is clicked ?

    if yes you need to have event handlers for them.

    just like

     Button button1 = new Button();
                button1.Click += Button1_Click;
     private void Button1_Click(object sender, EventArgs e)
                throw new NotImplementedException();

    Mark Answered, if it solves your question and Vote if you found it helpful.
    Rohit Arora

    Wednesday, April 12, 2017 12:14 PM
  • Hello,

     Most Methods return an object type. Rarely are any that do not or return void. 

    Below is an example of what you want to know.

     MSDN Ref:

     Hope this helps :)

    Wednesday, April 12, 2017 10:58 PM
  • Greetings Manoj.

    I'm not certain what you are asking, but maybe this is the answer.

             Button accept = null;
             Button cancel = null;
             foreach (Control control in Controls)
                Button button = control as Button;
                if (button != null)
                   if (button.DialogResult == DialogResult.OK)
                      accept = button;
                   if (button.DialogResult == DialogResult.Cancel)
                      cancel = button;
             if (accept != null && cancel != null)
                MessageBox.Show(" The default and cancel buttons are => " + accept.Text + " and => " + cancel.Text);

    Thursday, April 13, 2017 12:20 AM
  • Yes. You can show the Default button and Cancel button of current form using .AcceptButton and .CancelButton respectively.

    I'd recommend you to use .Name instead of .ToString() to show what the control is if it's for debug purpose, however. .ToString() can turn the value of .Text instead of .Name. When you have multiple control on the form with same text on it, this can be confusing.

    Thursday, April 13, 2017 1:34 AM