将尝试仅发布相关代码,因为我的程序已经很大了。基本上,该程序将客户信息添加到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;'确保它不是导致问题的变量,并且异常仍然发生。我几乎没有想法。问题不能与struct或arraylist定义一样,因为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;
但是在消息框提示工作后得到相同的异常后,我重写了上面的内容,但我仍然遇到问题,所以我不知道是什么导致它。
答案 0 :(得分:0)
datalist
中没有任何内容。可能recordCount
中LoadData
的值也为零。试试这个:
if(datalist.Count != 0) { /* Get the current record */ }