Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a MessageBox in C#?

Tags:

I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.

I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in

MessageBox("Hello, World!"); 

I received the following error:

MessageBox is a 'type' but used as a 'variable'

Fair enough, it seems in C# MessageBox is an Object. I tried the following

MessageBox a = new MessageBox("Hello, World!"); 

I received the following error: MessageBox does not contain a constructor that takes '1' arguments

Now I am stumped. Please help.

like image 831
Nick Stinemates Avatar asked Sep 08 '08 04:09

Nick Stinemates


People also ask

What is MessageBox class explain MessageBox () in detail?

A message box is a prefabricated modal dialog box that displays a text message to a user. You show a message box by calling the static Show method of the MessageBox class. The text message that is displayed is the string argument that you pass to Show.


2 Answers

MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like

if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {      //some interesting behaviour here } 

which I guess is a bit unwieldy but it gets the job done.

See https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here.

like image 160
Merus Avatar answered Sep 18 '22 13:09

Merus


Code summary:

using System.Windows.Forms;  ...  MessageBox.Show( "hello world" ); 

Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.

like image 45
moobaa Avatar answered Sep 21 '22 13:09

moobaa