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
Related
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);
I'm trying to add multiple lines and with different sections to a ListBox, and am required to use "\t" for creating a layout.
listBox.Items.Add(emp[index].first + "\t\t" + emp[index].last + "\t\t" + emp[index].number + "\t\t" + emp[index].department + "\t\t" + "Annual Salary: " + (emp[index].annualSalary).ToString("c") + ", Annual Bonus: " + (emp[index].annualBonus).ToString("c"));
Just one example line.
It comes out looking like: (without the dots)
Mary.......Sue................778-435-2321.....Accounting.....Annual Salary: $33,000.00
Trevor....Joseph...........604-894-2902.....Marketing.......Annual Salary: $52,000.00
Steve......Collin.............778-234-5432.....Finance..........Annual Salary: $48,500.00
George...........Watson..........604-910-2349.....Technical.......Annual Salary: $25,000.00
Sally.......Henderson.....604-654-2325.....Sales..............Annual Salary: $12,000.00
Jenny.....Motgomery.....604-692-4932.....Data Ana.......Annual Salary: $12,000.00
Can anyone explain why it's displaying all wonky, and how I might fix this?
I've searched online, but couldn't find any results using \t for layout.
First thing, I highly suggest using a pattern instead of concatenating your strings using plus sign. This will help you see things more clear:
string pattern = string.Format("{0}\t\t{1}\t\t{2}\t\t{3}\t\tAnnualSalary: {4}, Annual Bonus: {5}",
emp[index].first,
emp[index].last,
emp[index].number,
emp[index].department,
emp[index].annualSalary).ToString("c"),
emp[index].annualBonus);
The answer to your question is that you are using tabs assuming they will fill the space for you, but they won't. You need to use advanced features of
string.Format or string.Pad
Full answer can be found here: Formatting a C# string with identical spacing in between values
This question already has answers here:
How can I use a percent % in FormatString without it multiplying by 100?
(4 answers)
Closed 9 years ago.
I want to format an Axis in a Chart. For this i have following line:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# " + unit + ";-0.# " + unit + ";0 " + unit + "}";
Example for unit = "Joule": Format = "{0.# Joule;-0.# Joule;0 Joule"}
It brings me a good result (e.g. 1.5 -> "1.5 Joule", -1.4 -> "-1.4 Joule").
But if unit = "%" the values are multiplicated by 100. Means 5 -> "500%", 1.3 -> "130%"... and that's wrong. Also some inputs like " %" (with a variable spaces in the string), "_%", "‰" multiplicate the numbers.
Is there a way to show a percent number and prevent this effect?
Please note that i have to use the Format in this form Format = "???"; and i don't want to manipulate any DataPoints (like every DataPoint / 100).
You can put literal characters in quotes to avoid them being interpreted as format codes:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# '" + unit + "';-0.# '" + unit + "';0 '" + unit + "'}";
Escape the percentage sign.
unit = #"\%";
or
unit = "\\%;
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);
}
I need to convert this line in one string, because my method "DisplayMessage" only accept 1 argument, so how can I do this?
_userOptions.DisplayMessage("\nFile Generated: " +
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) +
"\nTime Elapsed: {0} minute(s) {1} second(s)",
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n");
It looks like your DisplayMessage method does not allow for the string format. Try putting this entire content (everything inside the parenthesis of DisplayMessage) inside a String.Format() method. That will make it one string and still allow for the multiple parameters you are passing.
Your string indicates that you want to call the static Format method on the String class, like so:
_userOptions.DisplayMessage(string.Format(
"\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)\n",
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)),
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10));
However, this will give you a problem, as you have more parameters than you have placeholders in the string.
Additionally, given comments regarding the use of "\n" as a new line delimiter, unless you have a specific need for that specific format (and it does not seem that you do, you aren't indicating you are writing to a file, or to something where the data is going to an external system), it's better to use Environment.NewLine, which you can use like so (note, this still does not address the fact you have more parameters than you do placeholders:
_userOptions.DisplayMessage(string.Format(
"{0}File Generated: {1}{0}Time Elapsed: {2} minute(s) {3} second(s){0}",
Environment.NewLine,
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)),
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10));
var msg = String.Format("\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)\n", BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)), timeSpan.Minutes, timeSpan.Seconds);
_userOptions.DisplayMessage(msg);
This should do it...
I guess you want to use String.Format. This takes a string and replace {#} by the argument index.
Example:
String.Format("Hi {0}, welcome to Stack Overflow!", "ale");
You might want to have a look at How should I concatenate strings?
This is more elegant in my opinion:
string message = string.Format("{0}File Generated: {1}{0}Time Elapsed: {2} minute(s) {3} second(s) {4} milliseconds{0}",
"\n", BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)), timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
_userOptions.DisplayMessage(message);
Using Format there's no need to use any + operator on the strings.
I think, you can use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\n");
sb.Append("File Generated: ");
sb.Append(BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)));
sb.Append("\n");
sb.Append("Time Elapsed: ");
sb.Append(timeSpan.Minutes);
sb.Append(" minute(s)");
sb.Append(timeSpan.Seconds);
sb.Append(" second(s)");
sb.Append();
_userOptions.DisplayMessage(sb.ToString());
but i think, you have some bug: you have 2 parameters but actually is 3
Try this:
string s= String.Format(
"\nFile Generated: " +
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) +
"\nTime Elapsed: {0} minute(s) {1} second(s) {2} msec(s)\n",
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
_userOptions.DisplayMessage(s);
Find below.
string str = String.Format("\n" + "File Generated: " + BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) + "\n" + "Time Elapsed: " + " {0} minute(s)" + " {1} second(s)", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n");
_userOptions.DiplayMessage(str);
Hope this helps.
Instead of {0} and {1}, just use your arguments directly:
_userOptions.DisplayMessage("\n" + "File Generated: " + BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) + "\n" + "Time Elapsed:" + timeSpan.Minutes + "minute(s)" + timeSpan.Seconds + "second(s)" + timeSpan.Milliseconds / 10 + "\n");