Reputation: 1
I want to open other forms in my main Form. It is working but I have to create a function for every option in the menu. Can i create a function that when I click on a certain menu item it uses one function and in that function it searches which Form I want to open.
Here is the code I am using now:
class functionsHoofdvenster
{
// Scherm in scherm functie voor frmTeams
public void frmTeamsAanroep(frmHoofdvenster frmhoofdvenster)
{
// Scherm in scherm weergeven (bool wordt naar true veranderd als mdi.child aan staat)
bool gevonden = false;
// Form met naam frmTeams zoeken en selecteren
foreach (Form x in frmhoofdvenster.MdiChildren)
{
if (x.Text == "frmTeams")
{
x.Activate();
gevonden = true;
break;
}
}
if (gevonden == false)
{
frmTeams f = new frmTeams();
f.MdiParent = frmhoofdvenster;
f.Show();
}
}
// Scherm in scherm functie voor frmSpelers
public void frmSpelersAanroep(frmHoofdvenster frmhoofdvenster)
{
// Scherm in scherm weergeven (bool wordt naar true veranderd als mdi.child aan staat)
bool gevonden = false;
// Form met naam frmTeams zoeken en selecteren
foreach (Form x in frmhoofdvenster.MdiChildren)
{
if (x.Text == "frmSpelers")
{
x.Activate();
gevonden = true;
break;
}
}
if (gevonden == false)
{
frmSpelers s = new frmSpelers();
s.MdiParent = frmhoofdvenster;
s.Show();
}
}
}
And the main form where I call the function
// Logical Layer aanroepen als ll
Logical_Layer.functionsHoofdvenster ll = new Logical_Layer.functionsHoofdvenster();
private void teamsToolStripMenuItem_Click(object sender, EventArgs e)
{
ll.frmTeamsAanroep(this);
}
private void spelersToolStripMenuItem_Click(object sender, EventArgs e)
{
ll.frmSpelersAanroep(this);
}
Upvotes: 0
Views: 38
Reputation: 81610
You can try using generics and reflection to show or create your forms:
private void ShowForm<T>() {
bool formFound = false;
foreach (Form f in this.MdiChildren) {
if (f.GetType() == typeof(T)) {
f.Activate();
formFound = true;
}
}
if (!formFound) {
var f = Activator.CreateInstance(typeof(T));
((Form)f).MdiParent = this;
((Form)f).Show();
}
}
Then you could call it like this:
ShowForm<frmTeams>();
ShowForm<frmSpelers>();
You would have to replace "this" with your MDI instance of frmHoofdvenster. My example assumes your child forms do not have custom constructors.
Upvotes: 1