Sorry for the weird title, I could't think of anything better!
Anyways, I'm half way through writing a program (Windows Forms App) that reads in a fixed-width file, gathers field lengths from user input, then it's supposed to display each column from the first line of the file in a different color... Do you know what I mean? It's basically to differentiate between the different fields in a fixed-width file using color.
What I wanted to ask was what was the best way to go about this? Because I'm having a lot of trouble, and I keep running into things and just implementing disgusting solutions when I know there is a much better one.
Obviously you don'开发者_JAVA百科t have to give me a whole program, just some ideas of better ways to go about this - because my solution is just horrendous.
Thank you all in advance!
I would use a RichTextBox. This has an easy way to change the color of text. Here is an example where I have 3 inputs from the user that tells how wide each column should be. Then it reads in a file and colors the widths appropriately. Hopefully this will give you some more ideas.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ReadFile();
}
private void ReadFile()
{
// Assumes there are 3 columns (and 3 input values from the user)
string[] lines_in_file = File.ReadAllLines(@"C:\Temp\FixedWidth.txt");
foreach (string line in lines_in_file)
{
int offset = 0;
int column_width = (int)ColumnWidth1NumericUpDown.Value;
// Set the color for the first column
richTextBox1.SelectionColor = Color.Khaki;
richTextBox1.AppendText(line.Substring(offset, column_width));
offset += column_width;
column_width = (int)ColumnWidth2NumericUpDown.Value;
// Set the color for the second column
richTextBox1.SelectionColor = Color.HotPink;
richTextBox1.AppendText(line.Substring(offset, column_width));
offset += column_width;
column_width = (int)ColumnWidth3NumericUpDown.Value;
// Make sure we dont try to substring incorrectly
column_width = (line.Length - offset < column_width) ?
line.Length - offset : column_width;
// Set the color for the third column
richTextBox1.SelectionColor = Color.MediumSeaGreen;
richTextBox1.AppendText(line.Substring(offset, column_width));
// Add newline
richTextBox1.AppendText(Environment.NewLine);
}
}
}
精彩评论