3
I’m making a sequence of screens in the form, I have a main screen that loads other screens, the main screen is the Form1
, and the subtleties will be the ones I will add on the main screen through the button
, but when I click several times on button
and start writing in TextBox
, I realize there’s a performance drop.
I found that when I assign the event TextChanged
of TextBox
that is on the main screen for the method TextBox_TextChanged()
of FormDefault
and when typing a certain amount of times into the TextBox
, the method TextBox_TextChanged()
is called how many times I clicked on button
formerly.
Example, I clicked 10 times on button
to carry the FormDefault
in the Form1
and entered the event of TextBox
in the TextBox_TextChanged()
, next time, when I write something on TextBox
the method TextBox_TextChanged()
will be called 10 times. Understand?
Imagine if this method makes a huge data query. This will get extremely slow.
public class Principal : Form
{
public Principal()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
FormDefault cd = new FormDefault();
this.textBox1.TextChanged += new EventHandler(cd.TextBox_TextChanged); // aqui esta o problema
cd.TopLevel = false;
cd.Visible = true;
this.Controls.Clear();
this.Controls.Add(cd);
}
public class FormDefault : Form
{
public FormDefault()
{
InitializeComponent();
}
public void TextBox_TextChanged(object sender , EventArgs e)
{
// se apertar no button duas vezes, esse método será repetido duas vezes
}
How do I assign only once the event TextChanged
of TextBox
to the method TextBox_TextChanged()
when I press the button
?
I understand, I’m gonna rethink the code
– sYsTeM