问题
i want read the each row and column but why it will pop out error message "make sure that the maximum index on a list is less than the list size".pls help...
string[] lines = File.ReadAllLines("C:\\test.txt");
for (int i = 0; i < lines.Length; i++)
{
string[] line = lines[i].Split('^');
for (int j = 0; j < line.Length; j++)
{
textBox1.Text = line[1];
break;
}
}
回答1:
I think you wanted to have j in the line
textBox1.Text = line[j];
instead of
textBox1.Text = line[1];
Or it won't work if there's more than one part in the line split by ^.
Full code:
string[] lines = File.ReadAllLines("C:\\test.txt");
for (int i = 0; i < lines.Length; i++)
{
string[] line = lines[i].Split('^');
for (int j = 0; j < line.Length; j++)
{
textBox1.Text = line[j];
break;
}
}
You may also consider changing the line textBox1.Text = line[j]; as it will overwrite the text in the loop.
EDIT
Based on the comment below, the code to read the first column from the first row is:
string[] lines = File.ReadAllLines("C:\\test.txt");
if (lines.Length > 0)
{
string[] line = lines[0].Split('^');
if (line.Length > 0)
textBox1.Text = line[0];
}
回答2:
Maybe you have an empty line or a line without ^. Because your accessing the second item in the array of strings here:
textBox1.Text = line[1];
perhaps you want to access always the first element, then use 0 since indices are zero based:
textBox1.Text = line[0];
However, more meaningful would be
textBox1.Text += line[j];
Since you are looping the columns anyway.
but i just want read row 1 and col 1 ...so how ??
Then you don't need a loop at all:
string firstLinesColumnOne = lines.Length > 0 ? lines[0].Split('^')[0] : "";
textBox1.Text = firstLinesFirstColumn;
if i want read each column and display to different text box? example text file is row1 {ab cd ef} row2 {dc fc fd} row3 {dg hj ki} so output should be textbox1 = column 1 textbox2 = column 2 textbox3 = column 3
Assuming you want to assign split three columns to three textboxes and add a new line for every line in the file in the textbox as well:
IEnumerable<String[]> lineColumns = lines
.Select(line => line.Split('^'));
textBox1.Lines = lineColumns.Select(cols => cols[0]).ToArray();
textBox2.Lines = lineColumns.Select(cols => cols[1]).ToArray();
textBox3.Lines = lineColumns.Select(cols => cols[2]).ToArray();
回答3:
for (int j = 0; j < line.Length; j++)
{
textBox1.Text = line[1];
if line.Length == 1 there is no line[1], there is only line[0]
来源:https://stackoverflow.com/questions/19421745/how-to-read-text-file-specifications-row-and-column-in-c-sharp