目前我有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);
答案 0 :(得分: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
}