Search code examples
c#.netwinformsdesktop

I am trying to loop through my data in text file and append it to list view


My textfile looks like this. Each value is on new row and I want to loop through this and show it into my listview. I want to loop through 7 lines for one listview row

husnain
zahid
john
UET society
lahore
22
Thursday April 14 2022
00000000
uzair
ejaz
doe
nasheman iqbal phase 2
 lahore
27
2022 ,اپریل 16
000000

and I am using this loop to loop through files and save show it into my listview

 private void LoadDataToListview()
    {
        var fileLines = File.ReadAllLines(@"E:\SCD_Project\Theory Assignments\A2\WindowsFormsApp1\WindowsFormsApp1\addressBook.txt");
        lineval = fileLines.Length;
        
        
        for (int i = 1; i < 16; i += 8)
        {
            S3_manageAddress_listview.Items.Add(
                 new ListViewItem(new[]
                 {
                        fileLines[i],
                        fileLines[i + 1],
                        fileLines[i + 2],
                        fileLines[i + 3],
                        fileLines[i + 4],
                        fileLines[i + 5],
                        fileLines[i + 6],
                        fileLines[i + 7],
     }));          
        }       
    }

Solution

  • Arrays in C# are zero based, so you need to start your iteration at 0 and not 1.

    private void LoadDataToListview()
    {
        var fileLines = File.ReadAllLines(@"E:\SCD_Project\Theory Assignments\A2\WindowsFormsApp1\WindowsFormsApp1\addressBook.txt");
        var groupSize = 8;
        //lineval = fileLines.Length;
       
        // start iterating at 0
        for (int i = 0; i < fileLines.Length; i += groupSize)
        {
            S3_manageAddress_listview.Items.Add(
                new ListViewItem(new[]
                {
                    fileLines[i],
                    fileLines[i + 1],
                    fileLines[i + 2],
                    fileLines[i + 3],
                    fileLines[i + 4],
                    fileLines[i + 5],
                    fileLines[i + 6],
                    fileLines[i + 7],
            }));
        }
    }