StackOverflow可能不是正确的原因,但是我正在寻找一个“原因”答案而不是“如何”答案。我已经通过禁用处理程序中的处理程序来解决此问题。
该应用程序具有一个DataGridView,可在进货检查期间显示库存信息。数据网格对于屏幕而言太宽,需要水平滚动。为了使数据更易于查看和编辑,添加了模态编辑器。有两个按钮可以关闭模式编辑器,即“保存”或“取消”。使用模式编辑器表单右上角的关闭按钮应执行与取消按钮相同的操作。
单击取消按钮后,一切正常。单击关闭按钮后,模式编辑器FormClosed事件将触发两次。为什么模式编辑器FormClosed事件会触发两次?我的代码中有错误吗?
private bool CancelModalEditor()
{
bool cancelled = false;
string cancelMsg = (_cancelClicked) ? "Canceling" : "Closing";
cancelMsg += " the editor will delete the Record with Serial Number: " + SerialNumber + " from the Audit Session. Is this what you want to do?";
DialogResult dlg = MessageBox.Show(cancelMsg, "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dlg == DialogResult.Yes)
{
SaveClicked = false;
}
else
{
cancelled = true;
}
return cancelled;
}
private void AEMEBtn_Cancel_Click(object sender, EventArgs e)
{
_cancelClicked = true;
if (!CancelModalEditor())
{
Close();
}
else
{
_cancelClicked = false;
}
}
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true; // Prevent Infite Loop
Close();
}
}
}
调用模式编辑器的文件。
private void ModalEditorForm_Closed(object sender, FormClosedEventArgs e)
{
AEModalEditor modalEditor = (AEModalEditor)sender;
int currentRow = modalEditor.RowID - 1;
if (modalEditor.SaveClicked)
{
UpdateDataGridRowWithModalEditorValues(dgAssetDetails, currentRow, modalEditor.AssetControlsValues);
updateAuditDetailsDataGridRow(currentRow, modalEditor.AuditControlsValues);
UpdateAuditTextFields(modalEditor);
SelectAllCellsInRow(currentRow);
}
else
{
DeleteRowFromAllDataGridViews(modalEditor.SerialNumber, currentRow);
_previouslySelectedRow = -1;
}
// Save all records in either case so that session data isn't lost.
save(false);
_currentlySelectedDataGrid = DataGrids.None;
_modalEditorOpen = false;
txtSerialNumber.Focus();
}
答案 0 :(得分:3)
不要在关闭事件中再次调用关闭。表单已经关闭,不需要再次关闭。
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true;
// You called Close here again
Close();
}
}
}