This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have the following calculated field in Vendor.cs:
public string FullAddress
{
get
{
return VendorAddNum + " " + TLRoadDirection.Direction + " " + VendorAddName + " " + TLRoadType.RdType + " " + TLUnitTypeOne.UnitType + " " + VendorAddUnitOne + " " + TLUnitTypeTwo.UnitType + " " + VendorAddUnitTwo;
}
}
Here's the markup from the view for the field:
#Html.DisplayNameFor(model => model.FullAddress)
When one of my vendors doesn't have any address information, FullAddress is null, which causes me to get a null reference exception. How can I allow FullAddress to be null?
Instead of concatenating all of the values, use string interpolation to better handle null values:
return $"{VendorAddNum} {TLRoadDirection.Direction} {VendorAddName} {TLRoadType.RdType} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {TLUnitTypeTwo.UnitType} {VendorAddUnitTwo}";
As an added bonus, the performance is a little better and the code is a little cleaner.
If you're using an older version of C#, you can use string.Format similarly:
return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", VendorAddNum, TLRoadDirection.Direction, VendorAddName, TLRoadType.RdType, TLUnitTypeOne.UnitType, VendorAddUnitOne, TLUnitTypeTwo.UnitType, VendorAddUnitTwo);
Related
This question already has answers here:
create a delimited text in c# with separate columns
(6 answers)
Closed 5 years ago.
First, my apologies if the title little strange, cause i'm little confused to make title for this problem.
Okay the problem is, it's possible using '\t' outside quote function on 'Console.WriteLine'. I've code like this.
Console.WriteLine("===============================================================================");
Console.WriteLine("| \tNo \t| \tProduct name \t| \tQty \t| \tPrice \t|");
Console.WriteLine("| \t1. \t| \tChicken Nugget \t|" + qty1 + price);
Console.WriteLine("| \t2. \t| \tTempe Nugget \t|" + qty2 + price);
Console.WriteLine("| \t3. \t| \tTofu Nugget \t|" + qty3 + price);
Console.WriteLine("===============================================================================");
So, i want to make variable (qty1, qty2, qty3, and price) parallel to column Qty and Price. It's possible?
result with code above
Console.WriteLine("===============================================================================");
Console.WriteLine("| \tNo \t| \tProduct name \t| \tQty \t| \tPrice \t|");
Console.WriteLine("| \t1. \t| \tChicken Nugget \t|\t" + qty1 + "\t|\t" + price + "\t|");
Console.WriteLine("| \t2. \t| \tTempe Nugget \t|\t" + qty2 + "\t|\t" + price + "\t|");
Console.WriteLine("| \t3. \t| \tTofu Nugget \t|\t" + qty3 + "\t|\t" + price + "\t|");
Console.WriteLine("===============================================================================")
Use string.format which gives you more control over formatting
I have some vehicle information that I want to send in an email.
I have all code working but spacing out the information is a problem. Each vehicle has a checklist and that checklist then gets emailed. So I loop through the list and get the defect and the comment.
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
defect += item.ItemTitle + " " + item.Comment + "\n";
}
}
if (hasDefect == true)
{
Utils.ChecklistSendMail("Checklist", ToAddresses.Split(';'),
"Vehicle Reg: " + reg + "\n" +
"Checklist No: " + chkList.CheckListNo + "\n"+
"Date: " + ChecklistDate.ToShortDateString() + "\n" +
"Defects: Comments: " + "\n" +
defect);
}
Email then looks like this:
Vehicle Reg: XLZ 8194
Checklist No: 0
Date: 22/03/2016
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
I want the defects and the comments to be displayed like this:
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
How do I evenly space out the defects and the comments?
You can use string.Format which supports automated padding:
string s = string.Format("{0,-20}{1}", "hello", "world");
Which outputs:
hello world
If you do that for every line, and you find a good distance (20 in my sample code), you will be fine. This all assumes the use of a mono-spaced font.
Use String.Format with the width specifier:
if (item.Defect == true)
{
defect += string.Format("{0,-20} {1,-10}\n", item.ItemTitle, item.Comment);
}
You could also use StringBuilder.AppendFormat if performance becomes an issue.
If you want to guarantee that the columns are aligned, even with a client that uses proportional fonts, then consider rendering as HTML and using a <table> instead.
I Have a messagebox to display some text and data (if existing) within database. The current Issue is trying to show nulls and trying to convert to ShortDate. I've taken two approach but none quite work in the way I need.
The first approach uses Ternary concatenation within the string but it behaves really weird.
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
Currently The message box only shows the line breaks and the Date Of birth. Not even the text "Date of Birth"
If I remove Tertiary and conversion and simply have
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This works, shows everything. Only issue is that the Date of birth is in the wrong format. Was wondering how do I make it so the date is in short date format and will show everything.
all Properties Of 'DuplicateName' are nullable,
I suspect this is a problem with operator precedence using the conditional operator. It's likely including string concatenations as part of the condition being tested, rather than as part of the result. You can explicitly enclose the elements of that operator with parentheses to identify which strings belong therein and which do not:
"\n Date of Birth: " + (DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ")
Additionally, if DOB is a DateTime? then you can simplify your code a little:
"\n Date of Birth: " + (DuplicateName.DOB.HasValue ? DuplicateName.DOB.Value.ToString("yyyy-mm-dd") : " ")
There's no need to use Convert on Nullable<T> types, you can more easily (and safely) make use of the HasValue and Value properties.
You can fix it by using another pair of parentheses:
(DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB))
In your first case, you're concatenating a huge string together (because you don't use any parentheses) and then testing that for null. It's equivalent to this:
var stringToTest = "A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB;
DialogResult DuplicateMessage =
MessageBox.Show(stringToTest != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This question already has answers here:
How to display the text in MVC?
(4 answers)
Closed 8 years ago.
I want to show a output in textbox in MVC. But its not displaying anything. I used the following code and i attached screenshot below:
#Html.TextAreaFor(up => up.CompileOutput)
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
return View(userProgram);
The first image shows that the output is binded with that particular textbox. But in browser (image 2) shows nothing in the textbox (red colour)
I am even wondering why you did not got an exception. return view(string) will look for a view with the string parameter as name, it will not show the text.
I would suggest you use ViewBag instead. So you set your error text in a property you name as follow:
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
ViewBag.ErrorText = userProgram.CompileOutput;
You can later on retrieve the value by simply calling ViewBag.ErrorText from you Razor view
Why not try doing it another way?
#Html.TextArea("CompileOutput", userProgram.CompileOutput)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
When trying to call my ToString() method I get the above error message. I'm not sure what the problem is. Here is my code:
public override string ToString()
{
return string.Format("{0} Pizzas # {1:C}: {2:C}\n" +
"{3} Cokes # {4:C} {5:C}\n" +
"Order Amount: {6:C}\n" +
"Sales Tax: {7:C}\n" +
"Amount Due: {8:C}\n" +
"Amount Paid: {9:C}\n" +
"Change Due: {10:C}", numberOfPizzas, PIZZA_PRICE +
totalCostOfPizza, numberOfCokes, COKE_PRICE, totalCostOfCoke +
foodAndDrinkTotal, totalSalesTax, totalAmountDue, amountPaid, +
changeDue);
}
You are referencing more arguments in the string format then you are providing.
By the looks of it, drop all the pluses (in the argument list not the string concatenation) and insert commas
It looks like you're adding things that you didn't mean to perhaps?
Try this:
public override string ToString()
{
return string.Format("{0} Pizzas # {1:C}: {2:C}\n" +
"{3} Cokes # {4:C} {5:C}\n" +
"Order Amount: {6:C}\n" +
"Sales Tax: {7:C}\n" +
"Amount Due: {8:C}\n" +
"Amount Paid: {9:C}\n" +
"Change Due: {10:C}", numberOfPizzas, PIZZA_PRICE,
totalCostOfPizza, numberOfCokes, COKE_PRICE, totalCostOfCoke,
foodAndDrinkTotal, totalSalesTax, totalAmountDue, amountPaid,
changeDue);
}