我有一个Windows Form
项目,它使用MDI
。我有一个方法负责保存任何可打开的可编辑窗体的数据,并为不同的事件调用此方法。但我也在父母的表格before close
事件中使用它,我需要检查所有打开的MDIchild,如果它们之间有可编辑的表单,并且如果有,请求保存。除此之外,我只关心ActiveMdiChild
是否可编辑,并要求仅为其保存。一种方法有两个几乎相同的if条件;是否有可能优化代码
下面是做好这项工作的方法:
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
是一种形式,大家甚至继承父窗体。现在我已经完成了将代码放在一个方法中,所以现在我只调用这个方法,但困扰我的是这两个部分几乎完全相同,但我仍然无法弄清楚如何优化逻辑。
谢谢,会试试这个! – Leron