john garcia john garcia - 1 month ago 9
C# Question

Multiple message box showing in c#

I am making a one form application and created a hard coded class for my GUI and event handlers.

At first the messagebox is showing once but when I click another button it is showing multiple times, increasing every click of a button.

I have not yet created a unhandled exception is that something to do with that? And if it is unhandled exception how can I do it?

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");

}

Answer

Every time you click on btnInventoryAddFanbelt, you are adding another click event:

btnInventorySaveFanbelt.Click += new EventHandler(btnInventorySaveFanbelt_click);

Only add it once, usually best to do that in the constructor or through the designer. It can also be shortened to just:

btnInventorySaveFanbelt.Click += btnInventorySaveFanbelt_click;

Also, split3.Panel2.Controls.Clear(); does not dispose of the controls, it just removes them, so you are leaking memory here. Try using:

while (split3.Panel2.Controls.Count > 0) {
  split3.Panel2.Controls[0].Dispose();
}
Comments