1

私のプログラムはすでにかなり大きいので、関連するコードのみを投稿しようとします。基本的に、プログラムは顧客情報をarraylist-structに追加します。保存と保存、ファイルの読み込みは問題なく機能していますが、データを表示しようとすると例外が発生します。

メインコードのほとんどはフォームとは別のクラスにあり、この特定の呼び出しは「frmViewRecords」からのものです。

public void ViewData(int currentRecord)
    {
        string fn = ((custDetails)datalist[currentRecord]).firstName;

        frmViewRecords viewRecords = new frmViewRecords();
        viewRecords.WriteData(fn);
    }

上記のコードが例外の原因ですが、以下のメッセージボックスのコードは正常に機能します。

public void LoadData()
    {
        bool fileLoaded = false;

        //Load the database
        try
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); //Create the filestream
            try
            {
                BinaryFormatter bf = new BinaryFormatter(); //New binary formatter for deserialization
                datalist = (ArrayList)bf.Deserialize(fs);
                fileLoaded = true; //Update the fileLoaded bool so that it doesn't open the file dialog instance
                recordCount = datalist.Count;
                MessageBox.Show("" + filename + " loaded successfully."); //Inform the user that the file was automatically loaded
                MessageBox.Show("Test: " + ((custDetails)datalist[0]).firstName);
            }
            catch
            {
                MessageBox.Show("Could not de-serialise from " + filename, "FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            fs.Close();
        }
        catch
        {
            if (MessageBox.Show("File isn't in the right location, this is normal if a dataset does not yet exist.\n\n If the file exists elsewhere click no and you will be prompted to find the database file, else click yes to create a default file.", "FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                fileLoaded = true;
                CreateDefaultData();
            }
        }

'string fn =((custDetails)datalist [0])。firstName;'を試しました 問題の原因となっている変数ではなく、例外が引き続き発生することを確認します。私はほとんどアイデアがありません。LoadData()のメッセージボックスが正常に機能し、正しい情報を出力するため、構造体または配列リストの定義で問題が発生することはありません。メッセージボックスをViewDataメソッドに移動しようとしましたが、それでも例外が発生し始めたので、メソッドに何か問題があるとしか想定できませんか?

これらのメソッドは「MainClass.cs」にあり、以下はfrmViewRecordsからメソッドを呼び出す方法です。

MainClass mainClass = new MainClass();
int currentRecord = 0;

private void LoadData()
    {
        mainClass.ViewData(currentRecord);
    }

以前は、次のようにfrmViewRecordsから直接データを呼び出していたことに言及する価値があるかもしれません。

txtFirstName.Text = ((MainClass.custDetails)mainClass.datalist[currentRecord].firstName;

しかし、メッセージボックスプロンプトが機能しているときに同じ例外が発生した後、それを上記に書き直しても問題が発生するため、何が原因であるかわかりません。

4

1 に答える 1

0

にアイテムはありませんdatalist。おそらく、のの値recordCountLoadDataゼロです。これを試して:

if(datalist.Count != 0) { /* Get the current record */ }
于 2012-11-27T14:06:21.750 に答える