-3

目前我有 2 个表格。Form1有一些选项卡控件。我想关闭标签页Form2。Form1 是 MDI 表格。Form2 是子窗体。Form2 位于 Form1 的标签页中。我只想将关闭按钮放入 Form2 以关闭 Form1 中的标签页。

Form2:

private void btnClose_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    frm.tabControl1.TabPages.Remove(frm.tabPage1); 
}

此代码没有错误,但在 vs2010 中不起作用。也尝试过RemoveAt, RemoveByKey。结果是一样的。

注意:我解决了以编程方式将按钮从 Form1 添加到 Form2 的问题。

Form1;

Button btn = new Button();
btn.Text = "X";
btn.Width = 23;
btn.Height = 23;
btn.FlatStyle = FlatStyle.Flat;
btn.Location = new Point(2, 3);
Form2 frm = new Form2();
frm.Controls.Add(btn);
4

1 回答 1

0
public class Form1 : Form
{
    //Delegate stuff for performing on UI thread.
    private delegate void TabPageDelegate(TabPage tab);
    private void RemoveTabOnUi(TabPage tab)
    {
        tabControl1.TabPages.RemoveAt(tab);
    }
    //internal method that will be accessible to other members of this namespace.
    internal void RemoveTab(TabPage tab)
    {
        //Do this action on UI delegate.
        this.Invoke(new TabPageDelegate(RemoveTabOnUi), tab);
    }

    //... Form1 Stuff
}
public class Form2 : Form
{
    public Form2()
    {
       //Add event to the closing event handler
       this.Closing += OnClosing;
    }
    private void OnClosing(object sender, EventArgs e)
    {
       //Check to make sure that MdiParent and Parent are correct
       if(null != this.MdiParent && this.MdiParent is Form1 && 
              null != this.Parent && this.Parent is TabPage)
       {
           //Calls the Form1().RemoveTab() internal method 
           ((Form1)this.MdiParent).RemoveTab((TabPage)this.Parent);
       }
    }

    //... Form2 Stuff
}
于 2013-02-26T22:44:25.183 回答