Home > Software design >  How do you populate a ListBox with items read from a text file
How do you populate a ListBox with items read from a text file

Time:04-01

So I tried reading the file and I confirmed it worked and then tried adding the contents to a listbox and it did not work. The way I do it is first read the file, split the file line by line and put the contents into a string array, then use a for loop to add the contents to a listbox. At first my problem was the listbox not having the contents added, then something changed and now it looks like the file isn't being read properly. I don't know if it affects anything but I did edit the file in Visual Studio so I wouldn't think that affect anything, but I'm mentioning it just in case. I am also using holdLine more than once since I am reading more than one file.

Here is where I am reading the file


using (StreamReader inOFile = new StreamReader("..\\..\\options.txt"))
{               
    while (!inOFile.EndOfStream)
    {
        holdLine = inOFile.ReadLine();
        OptionsArr = holdLine.Split('\n');  
    }

The file in question has these lines

  • Employee ID
  • Name
  • Department
  • Employment Status
  • Salary

The code where I try to add the contents of the string array to the listbox

OptionsListBox.Items.Clear();

OptionsListBox.BeginUpdate();
           
//one way I tried            
string listOptions = string.Join(" ", Program.OptionsArr);
OptionsListBox.Items.Add(listOptions.ToString());
              
//different way i tried
for (int i = 0; i < Program.OptionsArr.Length; i  )
{                 
    OptionsListBox.Items.Add(Program.OptionsArr[i]);
}
                  

//another failed attempt
OptionsListBox.Items.AddRange(Program.OptionsArr);

OptionsListBox.EndUpdate();

CodePudding user response:

Try something like :

// Employee is a class with employee fields (EmployeeID, name...)
IList<Employee> employees = readEmployeesFromFile();
OptionsListBox.DataSource = employees;
OptionsListBox.DisplayMember = "Name";
OptionsListBox.ValueMember = "EmployeeID";

CodePudding user response:

Here is some code that demonstrates the problem. I added some Console.WriteLine() to print out what is in the variables during and after the loop. (here is a fiddle)

using System;
using System.IO;
                    
public class Program
{
    const string _textFile = "This is the first line in the file\n"
                             "This is the second line in the file\n"
                             "This is the third line in the file\n";
    public static void Main()
    {
        var utf8 = System.Text.Encoding.UTF8.GetBytes(_textFile);
        var memoryStream = new MemoryStream(utf8);
        memoryStream.Position = 0;
        
        string wholeLine;
        string[] optionsArray;

        using (var inOFile = new StreamReader(memoryStream))
        {           
            var count = 0;
            while (!inOFile.EndOfStream)
            {
                wholeLine = inOFile.ReadLine();
                optionsArray = wholeLine.Split('\n');
                
                Console.WriteLine("Reading Line {0}",   count);
                Console.WriteLine("\tWhole: '{0}'", wholeLine);
                Console.WriteLine("\tSplit: '{0}'", string.Join("', '", optionsArray));
                Console.WriteLine()
            }
            Console.WriteLine("Final Options Array: {0}", string.Join(" | ", optionsArray));
        }
    }
}

The output of this program is:

Reading Line 1
    Whole: 'This is the first line in the file'
    Split: 'This is the first line in the file'

Reading Line 2
    Whole: 'This is the second line in the file'
    Split: 'This is the second line in the file'

Reading Line 3
    Whole: 'This is the third line in the file'
    Split: 'This is the third line in the file'

Final Options Array: This is the third line in the file

Notice how optionsArray only contains one item in it? And it's exact copy of wholeLine? That's because the ReadLine() function removes all the line breaks in the data. .Split('\n') won't be able to split anything.

If I change the split character to a space, then I get this:

Reading Line 1
    Whole: 'This is the first line in the file'
    Split: 'This', 'is', 'the', 'first', 'line', 'in', 'the', 'file'

Reading Line 2
    Whole: 'This is the second line in the file'
    Split: 'This', 'is', 'the', 'second', 'line', 'in', 'the', 'file'

Reading Line 3
    Whole: 'This is the third line in the file'
    Split: 'This', 'is', 'the', 'third', 'line', 'in', 'the', 'file'

Final Options Array: This | is | the | third | line | in | the | file

In this case, each line is split into separate words because they are separated by a space ' '. But even if I change the splitting, optionsArray only contains the last line in the file. Your while loop is written to read the entire file, but since you never do anything to collect the results of the split operating, the rest of your code won't do anything.

  • Related