Invoke MDI Child by name

J

Jassim Rahma

Hi,


I have MDI Child called MDIChild_! and I want if the user click on the
button which shows that form to invoke the same openned form not a new
form everytime unless it's not openned then it should open a new form.


Best Regards,
Jassim Rahma
 
C

Christiaan van Bergen

Hi Jassim,

First of all, if the name of the "MDI_Child_!" it will not work. The
exclamation-mark is not allowed.

What you want could be done with the so called "singleton" pattern.
Have your MDI Parent contain a variable for your child-form.

private frmChild childForm = null;

Second make a property in your parent form that will give you an instance of
that child.

private frmChild ChildForm
{
get{
if (childForm==null)
{
childForm = new frmChild();
childForm.MdiParent = this;
}
return childForm;
}
}

Now you could use this property in your button-click to open the childform

private void button1_Click(object sender, System.EventArgs e)
{
ChildForm.Show();
}


HTH
Christiaan
 
K

kHSw

I've posted a possible solution on my blog about a year ago, have a look at
http://khsw.blogspot.com/2004/11/load-mdi-child-by-only-passing-name.html

The example is in VB.NET, so here's the C# code:


Create this function to see if a form is already loaded:

private Form FormAlreadyLoaded(string formName)
{
foreach (Form frm in this.MdiChildren) {
if (frm.Name.ToUpper.Equals(formName.ToUpper)) {
return frm;
}
}
return null;
}


Add this function to load the form:

private void LoadForm(string formToLoad)
{
Form frm = FormAlreadyLoaded(formToLoad);
if (frm == null) {
frm =
((Form)(Reflection.Assembly.GetExecutingAssembly.CreateInstance(Reflection.Assembly.GetExecutingAssembly.GetName.Name
+ "." + formToLoad)));
frm.MdiParent = this;
frm.Icon = this.Icon;
frm.Show();
frm.BringToFront();
} else {
if (frm.WindowState == FormWindowState.Minimized) {
frm.WindowState = FormWindowState.Normal;
}
frm.BringToFront();
}
}


Now you can open a form named Form1 by typing
LoadForm("Form1")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top