karhtik sha
karhtik sha

Reputation:

opening forms in c#

I had a button in first form .if i click the button the second form is opening ,if i click again same button in first form another second form is opening.i need to open only one second form only in c# .

Upvotes: 0

Views: 1482

Answers (4)

Lennaert
Lennaert

Reputation: 2465

I'd declare a private variable in the class with the button that contains a reference to the opened form.

If the button is clicked:

  • Check whether it is null,
  • If yes, create and show a new form, if no, don't do anything.

If it's about having exactly one form open, you might also check out form.ShowDialog(), which blocks the caller form until the new form is closed.

Upvotes: 0

Ian
Ian

Reputation: 34489

Well you could do a :

Form.ShowDialog()

This will prevent the user clicking the button on the first form, as the second form will keep focus until it is closed.

Or you could do

Form2 form2 = null;

void button_click(object sender, EventArgs e)
{ 
   if(form2 == null)
   {
      form2 = new Form2();
      form2.Disposed += new EventHandler(f_Disposed);
      form2.Show();
   }
}

void f_Disposed(object sender, EventArgs e)
{
   form2 = null;
}

Upvotes: 4

Jim H.
Jim H.

Reputation: 5579

If you provide some sample code, we'll have a more specific answer, but it sounds like you are instantiating a new form in your button click event. The first time you click the button, your second form (will/may) not exist, so create it and keep a reference to it local to your first form. Then the next time the button is clicked, show the form instead of recreating it.

Upvotes: 0

JoshJordan
JoshJordan

Reputation: 12975

Check to see if the form is already shown by storing a reference to it and using something like:

if(form2Instance.Visible==true)
    ....

Upvotes: 1

Related Questions