Reputation: 1944
What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code:
//Working code
var sep = ", ";
var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName;
//Erronous code
var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName;
The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one.
EDIT: Solved. As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :)
Upvotes: 1
Views: 226
Reputation: 67068
I prefer using string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)
Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string.
In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?"
Are you doing this in an Eval() or code behind etc....
One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string.
Upvotes: 8
Reputation: 4547
What error is it throwing? That could tell you alot about why it is crashing.
Your calls both look valid on the surface to me. I would suggest that you make sure LastName and FirstName are strings and not null. To be sure, I guess you could append .ToString()
to the end of FirstName and LastName.
Upvotes: 0
Reputation: 1500065
I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same.
Upvotes: 1
Reputation: 30021
There is really no difference in your two calls, I see no error. What exception are you getting. Joel Coehoorn's answer with regards to String.Join is perfect for what you need.
Upvotes: 1
Reputation: 415665
string.Join(sep, new string[] {myNewBO[0].LastName, myNewBO[0].FirstName});
Upvotes: 5