Row-like string with even spacing in between values - c#

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

Related

How to pass a variable to another ASP.net page

Okay so I have some c# that generated href anchor tags styled as list items and throws it onto an aspx page like so;
html += "<a href='../InspectionView.aspx' class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Now this is in a loop, the variables are pulled from a SQL database and used to populate that html string.
Now, what I'm trying to do is have it so when the user clicks on one of the generated hrefs, and is redirected to the next page, the variable inspectionID is passed forward. I thought there might be someway of storing it in the ID of the href tag but I dont know where to go from there.
Thanks a lot.
Add a query string parameter.
html += "<a href='../InspectionView.aspx?inspectionID='" + inspectionID + " class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
For reading on the receiving page:
string inspectionID = Request.QueryString["inspectionID"];
See
https://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(v=vs.110).aspx
a very simple way is to stick into a query string. Since this isn't a server control it might be the only way to it.
something like...
html += "<a href='../InspectionView.aspx?InspectionID="+HttpUtility.UrlEncode(Inspection_ID.ToString())+"&anyotherQSField="+HttpUtility.UrlEncode(anyotherQSFieldVariable) + "' class='list-group-item'> - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Then in InspectionView.aspx,get values with something like:
String strInspection_ID = Request.QueryString["InspectionID"];
You likely need to convert to string for this to work for the ID.
You dont have to use HttpUtility.UrlEncode for Inspection_ID but if you have other strings you want to use in QS that might contain spaces or other odd characters - it would be wise.

Creating SQL Statements from a Text File - C#

Good morning,
I´m trying to create a program to create statements in a .Sql document but i´m having some troubles.
this is my code so far:
string[] filas = File.ReadAllLines("c:\\temp\\Statements.txt");
StreamWriter sw = new StreamWriter("c:\\temp\\Statements.sql");
foreach (string fila in filas)
{
string sql = "INSERT ";
string[] campos = fila.Split(' ');
if (campos[0]== "1A")
{
sql += " INTO TABLE1 (field1) VALUES (" + campos[1] + ");";
}
else
{
sql += " INTO TABLE2 (field1,field2,field3) VALUES (" + campos[1] + "," + campos[2] + "," + campos[3] + ");";
}
sw.WriteLine(sql);
}
sw.Close();
{
the thing is:
I need to read a txt document (the lenght will change), and then transform it to a sql document with all the statements, there are only two tipes of lines starting in "1A" or "2B", example:
1A123456 456,67
2B123456 mr awesome great strt germany
1A123456 456,67
2B123456 mr awesome great strt germany
2B123456 mr awesome great strt germany
1A123456 456,67
1A123456 456,67
then im trying to "transform" that information on "inserts":
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE2 (REF,NAME,ADR) VALUES (B123456,mr awesome,great strt);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
INSERT INTO TABLE1 (REF,MONEY) VALUES (A123456,456,67);
my code is not working so well... i hope someone can help me a litte :).
regards.
Firstly I could not see space between 1A and 123456 . So if (campos[0]== "1A") will not work. Use contains method to do this check - if (campos[0].contains("1A"). you can alternately evaluate using startswith
Secondly you need to split 1A123456 to get A123456 .. you can use substring or similar functions for same. (Same for 2B)
Thirdly, you are splitting the string with ' ' - this could result in many more string than your anticipated strings. 2B123456 mr awesome great strt germany - in this case mr awesome great strt are all different. You need to put in logic to concatenate campos[1] & campos[2] and campos[3] & campos[1=4] in the case of 2B ....
Fourthly for the 1A case you need to split campos[1] using , as delimiter to get the two values you want
Hope this provides you enough guidance to solve your issue.
After some research and with the help from anil and Pikoh i found a good solution:
string mydate = DateTime.Now.ToString("yyyyMMdd");
string AÑO = DateTime.Now.ToString("yyyy");
string MES = DateTime.Now.ToString("MM");
string DIA = DateTime.Now.ToString("dd");
string sql = "INSERT ";
string[] campos = fila.Split(' ');
if (campos[0].StartsWith("1H"))
{
sql += "INTO TABLE (VALUES,VALUES,VALUES) VALUES (" + "'" + mydate + "'" + "," + "'" + campos[0].Substring(1, 8) + "'" + "," + "'" + campos[0].Substring(9, 7) + "'" + "," + "'" + campos[8] + "'" + ");";
Inserting data and manipulating strings was good, but now i have the last problem,
what happen if i need to make a "backspace" to an specific string because my logic cant pick the correct information? regards.

how to evenly space out information?

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.

Line up Characters

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"
Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')
Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm

String Format wrong format for % [duplicate]

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 = "\\%;

Categories

Resources