WinForm Interview Question(C#)

Q. There is a WinForm(Form1) with a Button(Open Form2). If the user clicks the button it should open another WinForm(Form2). If the user again click on the Button in Form1, he should get a message saying that Form2 is already open.

Ans: In Form1's Button click event add this code.

 private void Form1Bttn_Click(object sender, EventArgs e)

{
bool FormOpen = false;

//Application.OpenForms propety: Gets a collection of open forms
//owned by the application.
foreach (Form S in Application.OpenForms)
{
if (S is Form2)
{
FormOpen = true;
}
}

if (FormOpen == true)
{
MessageBox.Show("Form already open.");
}

else
{
Form MyForm = new Form2();
MyForm.Show();
}
}

0 comments:

Post a Comment