Windows forms messagebox yes no

I want to make simple Yes/No choiced MessageBox, but I think it is nonsense to design a form for that. I thought I could use MessageBox, add buttons, etc. to accomplish this. It is simple, but since there is no DialogResult returned, how do I retrieve the result?

Peter Mortensen's user avatar

asked Jun 14, 2010 at 11:30

Petr's user avatar

This should do it:

DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
    //do something
}
else if (dialogResult == DialogResult.No)
{
    //do something else
}

answered Jun 14, 2010 at 11:37

Mikael Svenson's user avatar

Mikael SvensonMikael Svenson

39.2k8 gold badges73 silver badges79 bronze badges

3

DialogResult dr = MessageBox.Show("Are you happy now?", 
                      "Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
   case DialogResult.Yes:
      break;
   case DialogResult.No:
      break;
}

MessageBox class is what you are looking for.

answered Jun 14, 2010 at 11:34

SwDevMan81's user avatar

SwDevMan81SwDevMan81

48.9k22 gold badges151 silver badges184 bronze badges

MessageBox.Show(title, text, messageboxbuttons.yes/no)

This returns a DialogResult which you can check.

For example,

if(MessageBox.Show("","",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
   //do something
}

SwDevMan81's user avatar

SwDevMan81

48.9k22 gold badges151 silver badges184 bronze badges

answered Jun 14, 2010 at 11:34

Ben Cawley's user avatar

Ben CawleyBen Cawley

1,61617 silver badges29 bronze badges

The MessageBox does produce a DialogResults

DialogResult r = MessageBox.Show("Some question here");

You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx

answered Jun 14, 2010 at 11:34

David's user avatar

DavidDavid

72.7k19 gold badges132 silver badges173 bronze badges

Use:

MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
    // Do something
}
else if (m == m.No)
{
    // Do something else
}

MessageBoxResult is used on Windows Phone instead of DialogResult…

Peter Mortensen's user avatar

answered Aug 6, 2013 at 7:46

Khateeb321's user avatar

Khateeb321Khateeb321

1,86123 silver badges25 bronze badges

You can also use this variant with text strings, here’s the complete changed code (Code from Mikael), tested in C# 2012:

// Variable
string MessageBoxTitle = "Some Title";
string MessageBoxContent = "Sure";

DialogResult dialogResult = MessageBox.Show(MessageBoxContent, MessageBoxTitle, MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
    //do something
}
else if (dialogResult == DialogResult.No)
{
    //do something else
}

You can after

.YesNo

insert a message icon

, MessageBoxIcon.Question

answered May 26, 2013 at 20:00

AxelS's user avatar

AxelSAxelS

3141 gold badge4 silver badges11 bronze badges

1

@Mikael Svenson’s answer is correct. I just wanted to add a small addition to it:

The Messagebox icon can also be included has an additional property like below:

DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

Peter Mortensen's user avatar

answered Dec 15, 2015 at 10:52

Alston Antony's user avatar

0

if (MessageBox.Show("Please confirm before proceed" + "\n" + "Do you want to Continue ?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)

{
//do something if YES
}

else

{
//do something if NO
}

It will Prompt a message box like this.

answered Oct 3, 2019 at 5:55

Sudhakar MuthuKrishnan's user avatar

Try this:

if (MessageBox.Show("Are you sure", "Title_here", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
    Do something here for 'Yes'...
}

answered Feb 11, 2020 at 17:52

Ken's user avatar

KenKen

1,25410 silver badges16 bronze badges

dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);

if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
    enter code here
}
else 
{
    enter code here
}

Check more detail from here

brasofilo's user avatar

brasofilo

25.6k15 gold badges91 silver badges179 bronze badges

answered Jun 15, 2014 at 19:29

Harsh's user avatar

HarshHarsh

111 bronze badge

Последнее обновление: 31.10.2015

Как правило, для вывода сообщений применяется элемент MessageBox. Однако кроме сообственно вывода строки сообщения данный элемент может устанавливать
ряд настроек, которые определяют его поведение.

Для вывода сообщения в классе MessageBox предусмотрен метод Show, который имеет различные версии и может принимать ряд параметров.
Рассмотрим одну из наиболее используемых версий:

public static DialogResult Show(
	string text,
	string caption,
	MessageBoxButtons buttons,
	MessageBoxIcon icon,
	MessageBoxDefaultButton defaultButton,
	MessageBoxOptions options
)

Здесь применяются следующие параметры:

text: текст сообщения

caption: текст заголовка окна сообщения

buttons: кнопки, используемые в окне сообщения.
Принимает одно из значений перечисления MessageBoxButtons:

  • AbortRetryIgnore: три кнопки Abort (Отмена), Retry (Повтор), Ignore (Пропустить)

  • OK: одна кнопка OK

  • OKCancel: две кнопки OK и Cancel (Отмена)

  • RetryCancel: две кнопки Retry (Повтор) и Cancel (Отмена)

  • YesNo: две кнопки Yes и No

  • YesNoCancel: три кнопки Yes, No и Cancel (Отмена)

Таким образом, в зависимости от выбора окно сообщения может иметь от одной до трех кнопок.

icon: значок окна сообщения. Может принимать одно из следующих значений перечисления MessageBoxIcon:

  • Asterisk, Information: значок, состоящий из буквы i в нижнем регистре, помещенной в кружок

  • Error, Hand, Stop: значок, состоящий из белого знака «X» на круге красного цвета.

  • Exclamation, Warning: значок, состоящий из восклицательного знака в желтом треугольнике

  • Question: значок, состоящий из вопросительного знака на периметре круга

  • None: значок у сообщения отсутствует

defaultButton: кнопка, на которую по умолчанию устанавливается фокус. Принимает одно из значений перечисления MessageBoxDefaultButton:

  • Button1: первая кнопка из тех, которые задаются перечислением MessageBoxButtons

  • Button2: вторая кнопка

  • Button3: третья кнопка

options: параметры окна сообщения. Принимает одно из значений перечисления MessageBoxOptions:

  • DefaultDesktopOnly: окно сообщения отображается на активном рабочем столе.

  • RightAlign: текст окна сообщения выравнивается по правому краю

  • RtlReading: все элементы окна располагаются в обратном порядке справа налево

  • ServiceNotification: окно сообщения отображается на активном рабочем столе, даже если в системе не зарегистрирован ни один пользователь

Нередко используется один параметр — текст сообщения. Но посмотрим, как использовать остальные параметры. Пусть у нас есть кнопка, в обработчике
нажатия которой открывается следующее окно сообщения:

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(
        "Выберите один из вариантов", 
        "Сообщение", 
        MessageBoxButtons.YesNo, 
        MessageBoxIcon.Information, 
        MessageBoxDefaultButton.Button1, 
        MessageBoxOptions.DefaultDesktopOnly);
}

MessageBox в Windows Forms

Однако нам не просто дается возможность установки кнопок в окне сообщения. Метод MessageBox.Show возвращает объект
DialogResult, с помощью которого мы можем узнать, какую кнопку в окне сообщения нажал пользователь. DialogResult представляет
перечисление, в котором определены следующие значения:

  • Abort: нажата кнопка Abort

  • Retry: нажата кнопка Retry

  • Ignore: нажата кнопка Ignore

  • OK: нажата кнопка OK

  • Cancel: нажата кнопка Cancel

  • None: отсутствие результата

  • Yes: нажата кнопка Yes и No

  • No: нажата кнопка No

Используем обработку выбора пользователя, изменив обработчик нажатия кнопки следующим образом:

private void button1_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show(
        "Окрасить кнопку в красный цвет?", 
        "Сообщение", 
        MessageBoxButtons.YesNo, 
        MessageBoxIcon.Information, 
        MessageBoxDefaultButton.Button1, 
        MessageBoxOptions.DefaultDesktopOnly);
		
	if (result == DialogResult.Yes)
        button1.BackColor=Color.Red;
    
	this.TopMost = true;
}

И теперь, если в окне сообщения мы выберем выриант Yes, то кнопка окрасится в красный цвет.

A message box or dialog box is used to interact with the users of your application. The purpose of using a message box may include notifying about a particular action e.g. success message after entering a record. Similarly, an error message if an operation was unsuccessful. In both cases, you may display the “OK” button in the message box with the message.

In other cases, you may display a message box for the user confirmation before performing a critical action e.g. deleting a record permanently. In that case, a Yes/No button in the dialog box makes sense.

In this tutorials, I will show you how to create various types of C# message box with code.

How to make message box work in Visual Studio?

If you are working in Visual Studio then you have to include the System.Windows.Forms by following this:

  • In your project name under “Solution Explorer” right click and select “Add Reference”.
  • There you can see a few tabs. Select “.Net” tab.
  • Now locate the System.Windows.Forms and press OK

The example of creating a simple message box

After taking the above steps, you need including the System.Windows.Forms namespace as used in the code below.

You may provide a message to be displayed and the title of the dialog box by using the MessageBox class’s show method. The following example simply displays a box with the OK button:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

using System;

using System.Windows.Forms;

class msgbox_example

{

static void Main()

{

string box_msg = «A Message Box with OK Button»;

string box_title = «Message Box Demo»;

MessageBox.Show(box_msg, box_title);

}

}

The result:

c# messagebox

An example of Yes/No message box

The Yes/No dialog box can be useful for asking users to choose an option between the two. For example, “Are you sure you want to delete this record?” Similarly, “Do you want to really quit?” and so on.

The example below shows a Yes/No message box:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

using System;

using System.Windows.Forms;

class msgbox_example

{

static void Main()

{

string box_msg = «Message Box with Yes / No Options»;

string box_title = «Yes No Dialog»;

MessageBox.Show(box_msg, box_title, MessageBoxButtons.YesNo);

}

}

The result:

c# messagebox-yes-no

Adding Cancel button in above dialog

You may use the YesNoCancel Enum value for creating a dialog with the third button i.e. Cancel in addition to the above two buttons. The code below shows how with the output:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

using System;

using System.Windows.Forms;

class msgbox_example

{

static void Main()

{

string box_msg_y_n_c = «Yes/No/Cancel Options»;

string box_title_y_n_c = «Yes No Cancel Dialog box»;

MessageBox.Show(box_msg_y_n_c, box_title_y_n_c, MessageBoxButtons.YesNoCancel);

}

}

C# yes-no-Calcel-box

Adding an icon example

By using the MessageBoxIcon Enum, you may specify an icon to be displayed with the message in the dialog box. A number of values for various types of icons can be used. For example:

  • Exclamation
  • Information
  • Question
  • Warning
  • Asterisk
  • Error
  • Hand
  • Stop
  • None

The following example shows a few message boxes with different icons:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

using System;

using System.Windows.Forms;

class msgbox_example

{

static void Main()

{

MessageBox.Show(«Exclamation Icon message box», «Dialog with Icon», MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

MessageBox.Show(«Warning Icon message box», «Dialog with Icon», MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

MessageBox.Show(«There was an error processing your request!», «Dialog with Icon», MessageBoxButtons.OK, MessageBoxIcon.Error);

MessageBox.Show(«Operation cannot be successful, Do you want to retry?», «Dialog with Icon», MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop);

}

}

As you execute this code, four dialog boxes should display with respective icons and messages.

Performing actions on different buttons

The message box with OK button only may be used for information purpose to the user, without performing any action. However, in the case of boxes with OK, Cancel, Yes and No, Retry buttons, you may require performing some action based on the user’s selection.

So, how to catch which button is pressed by the user?

For that, you may use a variable that catches the returned value. Then it can be used in an if statement and you may perform the desired action.

To demonstrate that, the following program displays a message box with Yes/No/Cancel buttons. As you click any button, another message box with “OK” button is displayed with its own message for each button:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

using System;

using System.Windows.Forms;

class msgbox_example_value

{

static void Main()

{

var selectedOption = MessageBox.Show(«Please Select a button?», «Dialog Value Demo», MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

// If the no button was pressed …

if (selectedOption == DialogResult.Yes)

{

       MessageBox.Show(«Yes is pressed!», «Yes Dialog», MessageBoxButtons.OK, MessageBoxIcon.Warning);

}

else if (selectedOption == DialogResult.No)

{

MessageBox.Show(«No is pressed!», «No Dialog», MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}

else

{

MessageBox.Show(«Cancel is pressed», «Cancel Dialog», MessageBoxButtons.OK, MessageBoxIcon.Error);

}        

}

}

C# messagebox-value

This div height required for enabling the sticky sidebar

C# MessageBox in Windows Forms displays a message with the given text and action buttons. You can also use MessageBox control to add additional options such as a caption, an icon, or help buttons. In this article, you’ll learn how to display and use a MessageBox in C# WinForms app. You will also learn how to use C# MessageBox class dynamically in code samples. 

C# MessageBox

MessageBox class has an overloaded static Show method that displays a message box with a message and action buttons. The action buttons can be OK and Cancel, Yes and No etc. Here are some of the options that can be used in C# message box.

Simple MessageBox

The simplest form of a MessageBox is a dialog with text and OK button. When you click OK button, the box disappears.

The following code snippet creates a simple Message Box.

string message = "Simple MessageBox";  
MessageBox.Show(message);

MessageBox with Title

The following code snippet creates a simple MessageBox with a title. 

string message = "Simple MessageBox";  
string title = "Title";  
MessageBox.Show(message, title); 

 MessageBox with Title

MessageBox with Buttons

A MessageBox can have different button combinations such as YesNo and OKCancel. The MessageBoxButtons enumeration represents the buttons to be displayed on a MessageBox and has following values.

  • OK
  • OKCancel
  • AbortRetryIgnore
  • YesNoCancel
  • YesNo
  • RetryCancel

The following code snippet creates a MessageBox with a title and Yes and No buttons. This is a typical MessageBox you may call when you want to close an application. If the Yes button is clicked, the application will be closed. The Show method returns a DialogResult enumeration.

string message = "Do you want to close this window?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.YesNo;  
DialogResult result = MessageBox.Show(message, title, buttons);  
if (result == DialogResult.Yes) {  
    this.Close();  
} else {  
    // Do something  
}

MessageBox with Buttons

MessageBox with Icon

A MessageBox can display an icon on the dialog. A MessageBoxIcons enumeration represents an icon to be displayed on a MessageBox and has the following values.

  • None
  • Hand
  • Question
  • Exclamation
  • Asterisk
  • Stop
  • Error
  • Warning
  • Information

The following code snippet creates a MessageBox with a title, buttons, and an icon.

string message = "Do you want to abort this operation?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;  
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);  
if (result == DialogResult.Abort) {  
    this.Close();  
}  
elseif(result == DialogResult.Retry) {  
    // Do nothing  
}  
else {  
    // Do something  
}

MessageBox with Icon

MessageBox with Default Button

We can also set the default button on a MessageBox. By default, the first button is the default button. The MessageBoxDefaultButton enumeration is used for this purpose and it has the following three values.

  • Button1
  • Button2
  • Button3

The following code snippet creates a MessageBox with a title, buttons, and an icon and sets the second button as a default button.

string message = "Do you want to abort this operation?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;  
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);  
if (result == DialogResult.Abort) {  
    this.Close();  
}  
elseif(result == DialogResult.Retry) {  
    // Do nothing  
}  
else {  
    // Do something  
}

MessageBox with Default Button

MessageBox with Message Options

MessageBoxOptions enumeration represents various options and has the following values.

  • ServiceNotification
  • DefaultDesktopOnly
  • RightAlign
  • RtlReading

The following code snippet creates a MessageBox with various options.

DialogResult result = MessageBox.Show(message, title, buttons,  
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,  
MessageBoxOptions.RightAlign|MessageBoxOptions.RtlReading);  

MessageBox with Message Options

MessageBox with Help Button

A MessageBox can have an extra button called Help button. This is useful when we need to display a help file. The following code snippet creates a MessageBox with a Help button.

DialogResult result = MessageBox.Show(message, title, buttons,  
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,  
MessageBoxOptions.RightAlign, true );  

MessageBox with Help Button

We can also specify a help file when the Help button is clicked. The following code snippet references a help file.

DialogResult result = MessageBox.Show(message, title,  
buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, "helpfile.chm");  

Summary

In this article, we discussed how to create and use a MessageBox in a Windows Forms application.

  • Remove From My Forums
  • Question

  • Hi some one let me know how to create a dialog box with 3 options like ‘Yes’, ‘No’ and ‘Cancel’ buttons on that. (i am working in C# windows appliaction)

Answers

  • Another with if, else if blocks:

    DialogResult result = MessageBox.Show("Do you wanna do something?", "Warning", 
    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
    if(result == DialogResult.Yes)
    {
       //code for Yes
    }
    else if(result == DialogResult.No)
    {
      //code for No
    }
    else if (result == DialogResult.Cancel)
    {
      //code for Cancel
    }
    

    Mitja

    • Marked as answer by

      Monday, August 1, 2011 8:32 AM

  • Windows forms designer is not supported for project targeting net core rider
  • Windows for limbo pc emulator
  • Windows forms datagridview таблица c
  • Windows font viewer что это
  • Windows forms combobox значение по умолчанию