Search code examples
c#winformsevent-handlingtoolstripmenu

Enable/Disable SubmenuItems on Mdi Parent form in C# using Windows Application?


on Mdi parent form i am calling my child forms using menu items. on Child form Load my Menu item should be disabled on child form closed it will again Enabled.., i try FormClosing event handler i get the answer..,

  private void btnMn1_Click(object sender, EventArgs e)
    {
        Forms.Cnblfrm cnbfrm = new Cnsmblfrm();
        cnsmbfrm.MdiParent = this;
        cnsmbfrm.Text = btnMn1.Text;
        cnsmbfrm.Show();
        this.btnMn1.Enabled = false;
        cnbfrm.FormClosed += new FormClosedEventHandler(cnsmbfrm_FormClosed);
    }

    void cnbfrm_FormClosed(object sender, FormClosedEventArgs e)
    {
        btnMn1.Enabled = true;
        //throw new NotImplementedException();
    }

by using the above code i am getting the answer but i have morethan 20 ChildForms. By using this method My coding is increasing...., there is any method instead of this....,


Solution

  • If I understand you right: you have 20 buttons where every button opens a specific form, right?

    If so, you can set the tag-property of each button to the form it opens. then you have to iterate through all buttons and set the click-event. All buttons have the same click-event. (let's call it btn_click)

    the code of btn_click can look like:

    private void btn_click(object sender, EventArgs e)
    {
       Button button = sender as Button;
       if(button == null)
          return;
       Form form = button.Tag as Form;
       if(form == null)
          return;
       form.MdiParent = this;
       form.Text = button.Text;
       form.Show();
       button.Enabled = false;
       form.Tag = button;
       form.FormClosed += FormClosed;
    }
    
    private void FormClosed(object sender, FormClosedEventArgs e)
    {
       Form form = sender as Form;
       if(form == null)
          return;
       Button button = form.Tag as Button;
       if(button == null)
          return;
       button.Enabled = true;
    }