我正在我的程序中創建一個保存選項,用於保存對文件的更改。我正在使用此代碼來保存並獲取MessageBox
以顯示進程的結果,我在此行上收到錯誤「對象引用未設置爲對象的實例」。從方法返回布爾值
SaveFileCheck = StockHandler.SaveChangesToFile();
這是我的代碼
private void Save_Click(object sender, EventArgs e)
{
bool SaveFileCheck = false;
var result = MessageBox.Show("Are you sure you want to Save the changes ?", "My Application",
MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result == DialogResult.Yes)
{
SaveFileCheck = StockHandler.SaveChangesToFile();
if (SaveFileCheck)
{
MessageBox.Show("The process was a success");
}
else
{
MessageBox.Show("The process failed please make sure that the file is not been used and try again");
}
//Save the file back
}
}
}
}
public bool SaveChangesToFile()
{
try
{
if (FileName != null)
{
using (StreamWriter Write = new StreamWriter(FileName, false))
{
foreach (Stock s in FileStockList)
{
Write.Write(s.ToString() + "\r\n");
}
}
}
else {
return false;
}
}
catch(IOException ex)
{
return false;
throw new ArgumentException("something went wrong an error" + ex + "is been cought");
}
return true;
}
'StockHandler'必須爲'null';你確定你正在實例化它嗎? (如'StockHandler = new StockHandler()') –
'StockHandler'爲'null',在調用方法之前爲其指定一個類實例 – BrokenGlass
SaveChangesToFile中的哪行引發異常?它是「foreach(FileStockList中的股票)」嗎?如果是這樣的話,那麼'FileStockList'仍然是'null' - 你忘了創建它。 –