简体   繁体   中英

Trying to load 4 lines of code from txt file into a rich textbox

This is my code. I have a richTextBox and I loaded a txt file into it. I have a combobox that shows the name of the employee. What im trying to do is make the rich textbox load 4 lines of text from the txt file when a record is selected from the combobox. The code from everything works except getting the 4 lines of text.

using (StreamReader reader = File.OpenText("employeeData.txt"))  `
{
    for (var i = 0; i < 5; i++)    
    {
        reader.ReadLine();     `

        numLines = employeeDataRichTextBox.Lines.Count();

    }
    employeeDataRichTextBox.Text = reader.ReadToEnd();
}

You are consuming the lines before setting them to the textbox, so nothing will be added.

Change the code to this:

using (StreamReader reader = File.OpenText("employeeData.txt")) 
{
      for (var i = 0; i < 4; i++)
          employeeDataRichTextBox.Text += reader.ReadLine() + "\r\n";
}

reader.ReadLine() reads current line and then advances to next line. Your code reads 4 lines but doesn't put them into any variable. Then, when the reader is on the fifth line, you are telling him to read from that line to end.

add varialbe outside the for loop

List<string> listOfLines = new List<string>()

modify

reader.ReadLine();

into

listOfLines.Add(reader.ReadLine());

and finally put those lines into textbox

employeeDataRichTextBox.Text = string.Join(Environment.NewLine, listOfLines.ToArray());

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM