Search code examples
c++buildervcltlistview

List index out of bounds with a TListView


I'm confused when I try to insert a String into a TListView using insert(int,String).

Here is my code:

void __fastcall TFrmNewPeta::showDefaultRute()
{
    std::string line;
    std::ifstream ifs;
    wisata.savedefaultT4Awal("DefaultDataAwal");
    wisata.savedefaultT4Jarak("DefaultDataJarak");
    wisata.savedefaultT4Tujuan("DefaultDataTujuan");
    ifs.open("DefaultDataAwal"); 
    try{
         if(ifs.is_open())
         {
             for(int indexfile=0;std::getline(ifs,line);++indexfile)
             {
                ListItemnew = ListView1->Items->Add();
                ListItemnew->Caption = String(IntToStr(indexfile+1));
                ListItemnew->SubItems->Insert(indexfile,line.c_str());
                //cbxtest->Items->Insert(indexfile,line.c_str()); //successfull

             }
         }
    }__finally{
        ifs.close();
    }
}

With this the compiler says "List Index out of bounds (1)" I've been tried for many times to find the way out but I got the same result.

But this one made me wonder, because when I try to test with ComboBox its works well.

cbxtest->Items->Insert(indexfile,line.c_str());

If there something wrong with my code?


Solution

  • try this

    void __fastcall TFrmNewPeta::showDefaultRute()
    {
        std::string line;
        std::ifstream ifs;
        wisata.savedefaultT4Awal("DefaultDataAwal");
        wisata.savedefaultT4Jarak("DefaultDataJarak");
        wisata.savedefaultT4Tujuan("DefaultDataTujuan");
        ifs.open("DefaultDataAwal"); 
        try{
             if(ifs.is_open())
             {
                 for(int indexfile=0;std::getline(ifs,line);++indexfile)
                 {
                    ListItemnew = ListView1->Items->Add();
                    ListItemnew->Caption = String(IntToStr(indexfile+1));
                    ListItemnew->SubItems->Add(line.c_str());
                    //cbxtest->Items->Insert(indexfile,line.c_str()); //successfull
    
                 }
             }
        }__finally{
            ifs.close();
        }
    }
    

    I hope this help your problems