Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
What should I do if I want to show two values in one message box?
I mean something like:

MessageBox.Show("Your name and age will be: " + name +age ,"New guy");


But this will only split two strings together so it's useless.
Posted
Comments
Sergey Alexandrovich Kryukov 14-Feb-12 11:39am    
This is still one value, which is fine. String concatenation is pretty bad. Use string.Format.
--SA

concatenating strings (using +) is generally considered bad practice.

use string.Format(). This allows you to provide any number of 'bits' to insert into a string and allows you to specify where, and what formatting to use

in your above example you would need:

C#
MessageBox.Show(string.Format("Your name and age will be: {0}{1}",name,age) ,"New guy");
 
Share this answer
 
Use this...
C#
MessageBox.Show("Your name and age will be: " + name +" "+ age ,"New guy");


OR
Use String.Formate function like this...
C#
MessageBox.Show(string.Format("Your name and age will be: {0}{1}",name,age) ,"New guy");
 
Share this answer
 
v4
I'm not a native English speaker, so I might miss the important point here, but I just don't get what "splitting something together" could mean.

For a quick message box you can do this:
C#
MessageBox.Show(
    "InitialStringLiteral"
        + integerVarialbe.ToString()
        + "IntermediateStringLiteral"
        + anotherVariable.ToString()
        + "EvenMoreStringLiteralStuff",
    "HeadingAfterTheComma"
);


You can even define what buttons and icon will be shown. Just see http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.show.aspx[^]

Aside from the message box, if you want to concatenate large amounts of strings, consider using a StringBuilder[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900