我有一个Windows Form
使用MDI
. 我有一个方法负责保存任何打开的可编辑表单中的数据,并且为不同的事件调用此方法。但我也在父表单before close
事件中使用它,我需要检查所有打开的 MDIchilds,如果其中有可编辑的表单,如果有,请求保存。除此之外,我只关心它ActiveMdiChild
是否可编辑并且只要求保存它。
这是完成这项工作的方法:
protected void AskForSaveBeforeClose(object sender)
{
//Get the active child
BaseForm activeChild = this.ActiveMdiChild as BaseForm;
//Casting to MainForm return null if the sender is child form
Form mainForm = sender as MainForm;
//If the before close event comes from the parent loop all forms
if (mainForm != null)
{
foreach (BaseForm f in MdiChildren)
{
if (f.isEditable == true)
{
if (MessageBox.Show("To Do Do You Want To Save from MainForm " + f.Text, "Status",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
{
f.Save();
}
}
}
}
//if the event is not from the parent's before close just ask for the active child
else if (mainForm == null && activeChild != null)
{
if (activeChild.isEditable == true)
{
if (MessageBox.Show("To Do Do You Want To Save from AC ", "Status",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
{
activeChild.Save();
}
}
}
}
BaseForm
是每个人都继承甚至父窗体的窗体。现在我已经完成了将代码放在一个方法中,所以现在我只调用这个方法,但困扰我的是这两个部分几乎相同,但我仍然不知道如何优化逻辑。