您将需要使用委托来解决此问题。
在您的控件背后的代码中,定义一个委托,您将使用它来告诉您的主窗体自行关闭。无论您希望在控件中的哪个位置关闭父窗体,您都将引发此自定义事件,该事件将由您的父窗体处理。例如,我们假设您想在控件中单击按钮时关闭父窗体
public delegate void CloseHostFormEventHandler(Object sender, EventArgs e);
public partial class MyControl : Control {
public event CloseHostFormEventHandler CloseFormEvent;
public closeButton_Clicked(object sender, EventArgs) {
// do your db stuff
// you could create your own class here and pass the object to your main form if you wanted
EventArgs myargs = new EventArgs();
// tell host form to close itself
CloseFormEvent(this, myargs);
}
}
现在在您的父窗体中,您将要处理控件引发的事件。
public partial class MyForm : Form {
public MyForm() {
InitializeComponent();
// ill assume your control was added via the designer and thus done in InitializeComponent()
// hook up event handler
mycontrol.CloseFormEvent += CloseFormEventHandler(closeformCallback);
}
protected void closeformCallback(object sender, EventArgs e) {
DialogResult = DialogResult.OK;
this.Close();
}
}