2

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.

eYe
  • 1,695
  • 2
  • 29
  • 54
tshdvs
  • 43
  • 5
  • George is a big man. You can never get this perfectly right, there is no point in avoiding a ListView with View = Details. – Hans Passant Apr 01 '15 at 20:23

1 Answers1

0

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

Community
  • 1
  • 1
eYe
  • 1,695
  • 2
  • 29
  • 54