出现bug的原因是我点击Main form中一个按钮,弹出一个form窗口A,然后A关闭的时候,返回Main。然后发现操作的次数多了就会出现上述bug,刚开始以为是创建句柄出错,写了下面一段代码:
/*窗体在InitializeComponent()的时候如果创建不成功,尝试在Form的子类中重写CreateHandle,如果创建不成功,通过RecreateHandle,一般都会成功的 */
protected override void CreateHandle()
if (!IsHandleCreated)
base.CreateHandle();
catch { }
finally
if (!IsHandleCreated)
base.RecreateHandle();
不过后来发现还是不管用,就以为是需要dispose操作,所以又加了一段代码:
using (AForm A = new AForm())
A.ShowDialog(this.Parent.Parent);
但是,后来经过测试,发现还是不行,最后,我觉得可能是从A返回Main的时候,是在Main的父窗口中new的Main,因此又换了种形式。
先在A中,定义一个事件委托,用于进入Main的load方法,更新Main中的数据,代码如下:
public event EventHandler LoadHandler; // 用于调用父窗体load事件委托
public void btnSave_Click(object sender, EventArgs e)
SaveData();
this.Close();
MessageBox.Show("数据保存成功!");
this.Dispose();
if (LoadHandler != null)
LoadHandler(sender, e);
然后在AForm的click事件中添加如下代码:
private void lbl_edit1_Click(object sender, EventArgs e)
using (AForm A = new AForm())
A.LoadHandler += this.AForm_Load;
A.ShowDialog(this.Parent.Parent);
经过这三处代码的修改,发现此bug解决了!!!