Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form from showing multiple times

Tags:

c#

winforms

In windows form (c#), i am showing a form when user click on button, it is working fine form is visible to user, but if user click again on the same button the same form is opening again two forms are displaying. Is there any way to prevent this, please give me any reference for this thank you. This is my code....

private void button1_Click(object sender, EventArgs e)
{
  Form2 obj = new Form2();
  obj.Show();
}
like image 788
Ssasidhar Avatar asked Sep 16 '25 22:09

Ssasidhar


2 Answers

You are most likely doing something like this:

void button1_OnClick(object sender, EventArgs e) {
    var newForm = new MyForm();
    newForm.Show();
}

So you are showing a new instance of the form every time it is clicked. You want to do something like this:

MyForm _form = new MyForm();

void button1_OnClick(object sender, EventArgs e) {
    _form.Show();
}

Here you have just one instance of the form you wish to show, and just Show() it.

like image 196
Jonathon Reinhart Avatar answered Sep 19 '25 01:09

Jonathon Reinhart


foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(MyFormType))
    {
        form.Activate();
        return;
    }
}

Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();

i tried more than a ways to compare which one is better.

but i think this solution must be better than the answer.

like image 25
Bobby Akyong Avatar answered Sep 19 '25 03:09

Bobby Akyong