Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Message Box, variable usage

I have searched but I dont know if I am using the correct verbiage to search for. I am writing a program in C# for my class but I am having trouble with the message box.

I am trying to have the message box show a message and read a variable at the same time. I have no problem doing this in the console applications but I cannot figure it out for the Windows side.

So far I have:

MessageBox.Show("You are right, it only took you {0} guesses!!!", "Results", MessageBoxButtons.OK);

Which works fine. Howerver I am trying to have the {0} be the result of the variable numGuesses. I'm sure this is simple and I am just overlooking it in the book or something, or I have the syntax incorrect someplace.

like image 554
willisj318 Avatar asked Aug 20 '11 22:08

willisj318


4 Answers

try

MessageBox.Show(string.Format ("You are right, it only took you {0} guesses!!!", numGuesses ), "Results", MessageBoxButtons.OK);

see http://msdn.microsoft.com/en-us/library/system.string.format(v=VS.100).aspx

like image 126
Yahia Avatar answered Sep 20 '22 11:09

Yahia


You can use String.Format or simple string concatenation.

MessageBox.Show(String.Format("You are right, it only took you {0} guesses!!!", myVariable), "Results", MessageBoxButtons.OK);

http://msdn.microsoft.com/en-us/library/system.string.format(v=VS.100).aspx

Concatenation:

MessageBox.Show("You are right, it only took you " + myVariable + " guesses!!!", "Results", MessageBoxButtons.OK);

Both results are equivalent, but you may prefer String.Format if you have multiple variables in the same string.

like image 38
Evan Mulawski Avatar answered Sep 18 '22 11:09

Evan Mulawski


What about String.Format() ?

MessageBox.Show(String.Format("You are right, it only took you {0} guesses!!!", numGuesses), "Results", MessageBoxButtons.OK);
like image 25
Dalmas Avatar answered Sep 20 '22 11:09

Dalmas


String.Format is what you want:

string message = string.Format("You are right, it only took you {0} guesses!!!",numGuesses)

MessageBox.Show(message, "Results", MessageBoxButtons.OK);
like image 25
Joe Avatar answered Sep 19 '22 11:09

Joe