简体   繁体   中英

MessageBox.Show format

I just started learning C# so bear with me. I have been looking everywhere for help on this simple issue.

I have program that requires the user to guess a random number and after the number is guessed a message box appears that says your correct and how many guesses it took. I just moved from creating console apps to windows form apps and have painfully realized that its a different set of rules.

MessageBox.Show("You are right! It took you " +totalGuesses," guesses",MessageBoxButtons.OK);

I need the output to say that You are right! It took you 9 guesses.

what I end up getting is You are right! It took you 9 and guesses is the title of the messagebox.

Can someone tell me what I am doing wrong please.

This would be the correct method call:

MessageBox.Show("You are right! It took you " + totalGuesses + " guesses","Title of your Box",MessageBoxButtons.OK);

In c# methods could have different parameters, each seperated with ",". Methods could also be overloaded so that you can call the same method but with different parameters: So if you just want to display a message in a MessageBox you could write:

MessageBox.Show("Your Message");

If you want to add a title to your Message:

MessageBox.Show("Your Message", "Title");

IntelliSense is a good help for you in this case as it should show a short discription of the parameter each time you insert a "," in the method call.

In your case you put a "," in front of "guesses". The result is, that c# sees it as the second parameter which is the title of the box.

It is generally recommended to use String.Format for these types of things. Try the following:

var message = string.Format("You are right! It took you {0} guesses.", guesses);
MessageBox.Show(message, "Correct!", MessageBoxButtons.OK);

You can just use string.Format as well like;

MessageBox.Show(string.Format("You are right! It took you {0} guesses", totalGuesses), 
                "Caption",
                MessageBoxButtons.OK);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM