を使用するWindows Form
プロジェクトがありますMDI
。開いている編集可能なフォームからデータを保存するメソッドがあり、このメソッドはさまざまなイベントに対して呼び出されます。ただし、親のフォームbefore close
イベントでも使用します。このイベントでは、開いているすべてのMDI子をチェックし、編集可能なフォームがあるかどうかを確認し、ある場合は保存を要求します。それ以外は、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
親フォームも誰もが継承するフォームです。今のところ、コードを1つのメソッドにまとめることができたので、このメソッドのみを呼び出しますが、2つの部分がほぼ同じであるにもかかわらず、ロジックを最適化する方法がわかりません。