我正在创建一个表单应用程序,并为我的GUI和事件处理程序创建了一个硬编码类。
首先,消息框显示一次但当我点击另一个按钮时,它会多次显示,每次点击按钮都会增加。
我还没有创建一个未处理的异常,那与之有关?如果它是未处理的异常,我该怎么办呢?
private void btnInventoryAddFanbelt_click(object sender, EventArgs e)
{
// CONTENTS
// labels
lblFanbeltName.Name = "lblFanbeltName";
lblFanbeltName.Text = "Fanbelt name";
lblFanbeltName.Visible = true;
lblFanbeltName.Location = new Point(10, 10);
// textbox
txtFanbeltName.Name = "txtFanbeltName";
txtFanbeltName.Visible = true;
txtFanbeltName.Location = new Point(115, 8);
// buttons
btnInventorySaveFanbelt.Name = "btnInventorySaveFanbelt";
btnInventorySaveFanbelt.Text = "Add fanbelt";
btnInventorySaveFanbelt.Visible = true;
btnInventorySaveFanbelt.Location = new Point(125, 50);
// END OF CONTENTS
// REMOVE CONTROLS
split3.Panel2.Controls.Clear();
// ADD CONTROLS
split3.Panel2.Controls.Add(lblFanbeltName);
split3.Panel2.Controls.Add(txtFanbeltName);
split3.Panel2.Controls.Add(btnInventorySaveFanbelt);
// EVENTHANDLERS
btnInventorySaveFanbelt.Click += new EventHandler(btnInventorySaveFanbelt_click);
}
private void btnInventorySaveFanbelt_click(object sender, EventArgs e)
{
MessageBox.Show("Fanbelt added");
}
答案 0 :(得分:1)
每次点击btnInventoryAddFanbelt,您都会添加另一个点击事件:
btnInventorySaveFanbelt.Click += new EventHandler(btnInventorySaveFanbelt_click);
只添加一次,通常最好在构造函数中或通过设计器执行此操作。它也可以简化为:
btnInventorySaveFanbelt.Click += btnInventorySaveFanbelt_click;
此外,split3.Panel2.Controls.Clear();
不处理控件,它只是删除它们,所以你在这里泄漏内存。尝试使用:
while (split3.Panel2.Controls.Count > 0) {
split3.Panel2.Controls[0].Dispose();
}