rayden54
rayden54

Reputation: 251

Change the "length" of a tab delimited file in C#?

I've got a tab delimited file like so that I am reading into an array:

string[] yourChoicesItems = File.ReadAllLines("test.txt"); 
aaaaaaaaa(tab)0.09
aaa(tab)1.25

The problem is, when I display the array in a text box, it ends up looking something like this:

aaaaaaaaa    0.09
aaa    0.09

I want the 2nd column to line up. In Word, I'd just change the tab stops, but when I Googled "Tab stops" + C# I got something completely different.

Upvotes: 0

Views: 648

Answers (4)

Sten Petrov
Sten Petrov

Reputation: 11040

To line them up in your textboxes split your input then join it back with String.Format:

string[] parts= record.Split('\t');
string yourOutput = string.Format("{0,-15}{1}", parts[0], parts[1]);

Of course some input checking would be good... and what you're asking for still probably needs to be revised and have separate controls for each part you're showing

Upvotes: 1

Aleksandar Toplek
Aleksandar Toplek

Reputation: 2831

Take a look at this answer. You haven't specified whether you are using wpf or wf but it should be something similar.

Upvotes: 0

smartcaveman
smartcaveman

Reputation: 42246

string[] records = inputString.Split('\n');
foreach(var record in records)
{
   string[] fields = record.Split('\t');
   // do stuff with the fields, here, (independently of tabs) 
}

edit @JonSkeet beat me to it by 30 seconds, but I'm leaving this code sample b/c his answer lacks one

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500963

Fundamentally, text boxes aren't really designed to handle formatted text as far as I'm aware. There's RichTextBox of course - but I'm not sure even that would handle tabs the way that you want it to just by default.

With a plain text box you could set the font to something fixed-width, and then replace each tab with a different number of spaces depending on how far through the line it was... but that's a lot of faff to display fundamentally-tabular data in a control which really wasn't designed for that purpose.

You should consider something along the lines of a grid view instead - split the lines by tabs, and each line becomes a row of data. It's a much more appropriate control for the task at hand, I suspect.

Upvotes: 4

Related Questions