Include an if condition in message-box dialog code in c#

3.9k views Asked by At

I have a message box dialog which comes with yes no like following. I have added no button as default selected button in the code. I want to do this by checking an if condition. Based on the if condition result I want to set the default button in the message dialog. I am doing it with "MessageBoxDefaultButton.Button2 "Without repeating message box dialog in an if the condition is there a way that I can set this button checking a value using an if condition inside this dialog box code.

if (MessageBox.Show("Selected itemis already existing , Do you want to continue adding?", "XXX", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
   {

   }
2

There are 2 answers

0
Nishil On

I assume this is what you want.

bool myCondition = true;  

if (MessageBox.Show("Selected itemis already existing , Do you want to continue adding?", "XXX", MessageBoxButtons.YesNo, MessageBoxIcon.Question,myCondition? MessageBoxDefaultButton.Button2:MessageBoxDefaultButton.Button1) == DialogResult.Yes)  
{  
}
0
RezaNoei On

Store your Default Button in a MessageBoxDefaultButton:

MessageBoxDefaultButton DefaultButton = MessageBoxDefaultButton.Button1;

and use it:

if (MessageBox.Show("Selected itemis already existing , Do you want to continue adding?", "XXX", MessageBoxButtons.YesNo, MessageBoxIcon.Question, DefaultButton) == DialogResult.Yes)
{

}