Candy Lee
Candy Lee

Reputation: 41

How to align output text in C# .net

I have some datarows and I want to display them in a textbox;

This is some part of my code:

strDetails += "Challenge ID" + "\t" + "Challenge Name" + "\t\t" + "Start Time" + "\r\n\r\n";
strDetails += drChallenge["ChallengeID"] + "\t\t" + drChallenge["ChallengeName"] + "\t\t" + 
startTime.ToString("h:mm tt") + "\r\n";

However, the output has some issues with the time string. I dont know how to align them.

output

enter image description here

Upvotes: 0

Views: 189

Answers (2)

matheus-fofonka
matheus-fofonka

Reputation: 28

You can iterate a member of a columns, get a max lengh a column and take a padleft(max_lengh) all members at column to a max lengh.

Upvotes: 1

Simmetric
Simmetric

Reputation: 1651

The line where the time is out of band, has a Challenge Name of less than 8 characters. A tab spans (by default) 4 spaces. If the Challenge Name is more than 12 characters, the time field would go out of band to the other side.

The real solution is to use something intended for complex formatting. For example you could output a CSV file that can be opened by Excel, or use a layout language such as HTML.

If you really want to do this with text in a textbox then you can:

  • ensure Challenge Name is no longer than 11 characters
  • render the Challenge Name as drChallenge["ChallengeName"].PadRight(8, ' ') to ensure it's always at least 8 characters, filled with spaces.

Upvotes: 1

Related Questions