为什么System.IndexOutOfRangeException

时间:2014-03-09 10:35:40

标签: c++ visual-studio-2012 csv streamreader

我已经编写了下面的代码,当我运行它时,它说

System.IndexOutOfRangeException: L'index is outof the limites of table.
   in AddWindowsForm.MyForm.ReadCSV(StreamReader str) ind:\weiweiwang\signalisationferroviaire\visual studio 2012\projects\addwindowsform1213\addwindowsform1213\myform.h:line 7738
   in AddWindowsForm.MyForm.OpenFileDialogCSV_FileOk(Object sender, CancelEventArgs e) in d:\weiweiwang\signalisationferroviaire\visual studio 2012\projects\addwindowsform1213\addwindowsform1213\myform.h:line 7728
   in System.Windows.Forms.FileDialog.OnFileOk(CancelEventArgs e)
   in System.Windows.Forms.FileDialog.HandleVistaFileOk(IFileDialog dialog)

我不明白为什么......

private: System::Void OpenFileDialogCSV_FileOk(System::Object^  sender, System::ComponentModel::CancelEventArgs^  e) {
            InitialiserDonnees(); 
            strFileDirectoryName=OpenFileDialogCSV->InitialDirectory+OpenFileDialogCSV->FileName;
            StreamReader ^strReadFile=gcnew StreamReader (strFileDirectoryName);
            String ^strL="";            
            MyForm::Text="Aide aux calculs des distances:" + System::IO::Path::GetFileName(OpenFileDialogCSV->FileName);
            ReadCSV(strReadFile);           
         }



public: void ReadCSV ( StreamReader ^str)   
        {
            array<String^>^temp=gcnew array <String^> {"","","","","","","","","","",""};
            String ^strL="";
            //Read Info Poste et track
                    strL=str->ReadLine();
                    strL=str->ReadLine();
                    temp=strL->Split(';');
                    textBoxNomPoste->Text=temp[1];

                    strL=str->ReadLine();
                    temp=strL->Split(';');
                    textBoxNomVoie2->Text=temp[1];

                    strL=str->ReadLine();
                    temp=strL->Split(';');
                    comboBoxImpairPair->Text=temp[1];

                    strL=str->ReadLine();
                    temp=strL->Split(';');
                    ComboBoxNbDeclivite->Text=temp[1];
}

1 个答案:

答案 0 :(得分:1)

System.IndexOutOfRangeException异常表示您正在访问具有无效索引的数组或容器。也就是索引指的是一个不存在的项目。在代码中,您在访问temp数组时使用数组索引。您尝试在此处访问索引为1的项目:

temp[1]

错误通知您temp不包含索引为1的项目。

您在此处指定了temp

temp=strL->Split(';');

显然,对Split()的调用结果是一个少于2个元素的数组。检查strL的内容,了解其原因。

请注意这行代码:

array<String^>^temp=gcnew array <String^> {"","","","","","","","","","",""};

完全没有意义,因为在分配不同的值之前,你从未读过temp的值。