I am currently working on a windows form application. I need to read text from a particular file, i am not sure of the number of lines that will be in this text file at a given time but i need to retrieve each line and display them on a form page. i have tried to store the string in an array but i get an error "Make sure that the maximum index on a list is less than the list size".
Also note that i have created some labels on certain positions for each lines, (i made about ten labels). This is the portion of the code giving me problem:
string[] edfTaskList = System.IO.File.ReadAllLines(edfTaskfile);
oldtask1.Text = edfTaskList[0];
oldtask2.Text = edfTaskList[1];
oldtask3.Text = edfTaskList[2];
oldtask4.Text = edfTaskList[3];
oldtask5.Text = edfTaskList[4];
oldtask6.Text = edfTaskList[5];
oldtask7.Text = edfTaskList[6];
oldtask8.Text = edfTaskList[7];
oldtask9.Text = edfTaskList[8];
oldtask10.Text = edfTaskList[9];
oldTaskPanel.Controls.Add(oldtask1);
oldTaskPanel.Controls.Add(oldtask2);
oldTaskPanel.Controls.Add(oldtask3);
oldTaskPanel.Controls.Add(oldtask4);
oldTaskPanel.Controls.Add(oldtask5);
oldTaskPanel.Controls.Add(oldtask6);
oldTaskPanel.Controls.Add(oldtask7);
oldTaskPanel.Controls.Add(oldtask8);
oldTaskPanel.Controls.Add(oldtask9);
oldTaskPanel.Controls.Add(oldtask10);
I would do something like this:
private int lastLablePos;
public Form1()
{
InitializeComponent();
lastLablePos = panel1.Location.Y;
}
private void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(@"D:\test.txt");
Label[] labels = new Label[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
labels[i] = new Label();
labels[i].Text = lines[i];
}
foreach (Label lable in labels)
{
lable.Location = new Point(0, lastLablePos);
lable.AutoSize = true;
panel1.Controls.Add(lable);
lastLablePos += 30;
}
}
and finally add those labels to form with coordinates etc.
Are you sure that the array totally got 10 or more entries? I guess that this is the problem, you are addressing more values than you actually have.
Either loop through your entries (by using a foreach loop) and create your labels dynamically or use other control elements as Saverio Terracciano mentioned.
使用File.ReadLines代替File.ReadAllLines并使用DataGrid显示数据,请参见File.ReadLines
There are several different approaches you could use to solve your problem, which is rather broad, assuming you have no way to have an upperbound on the number of lines you could:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.