question about msgbox in c#

A

Adam Sandler

Hello,

I'm converting this code from VB:

Try
With serialPort
' snip
End With
Catch ex As Exception
MsgBox(ex.ToString)
End Try

And this is what I have:

try
{
// snip
}
catch (Exception ex)
{
MsgBox(ex.ToString);
}

I get an error which states, "The name 'MsgBox' does not exist in the
current context". I have "using System.Windows.Forms;" at the top of
the code.

So I did some looking around and found a couple of sites which say to
do this:

System.Windows.Forms.MessageBox.Show("Test");

But when I do either "MessageBox.Show("Test");" or "
MessageBox(ex.ToString);" I get this error
"System.Windows.Forms.MessageBox is a 'type' but is used like a
'variable'".

I'm really confused, I'm using the examples I see in other postings
and I have the required using statement... How can I get a msgbox to
appear on the screen? (I know this is a lousy example of handling an
exception... but the point of my post is asking about getting a msgbox
to work.)

Thanks!
 
K

khmer_lovers

Hi Adam,

The correct way is

try
{
// snip
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString()); //ToString() is a method not
a property

//OR

MessageBox.Show(ex.Message);
}
 
B

Bruce Wood

So I did some looking around and found a couple of sites which say to
do this:

System.Windows.Forms.MessageBox.Show("Test");

But when I do either "MessageBox.Show("Test");"

This should work, so long as you have "using System.Windows.Forms;" at
the top of your program.
or "MessageBox(ex.ToString);" I get this error
"System.Windows.Forms.MessageBox is a 'type' but is used like a
'variable'".

Well, this won't work, because you are using the type as though it
were a method name. You forgot the ".Show()".

It would help us help you if you cut and pasted the actual code
snippet.

BTW, this is, in fact, the proper way to show a message box in C#.
You're on the right track. You just need to get the syntax straight.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top