在C#中在运行时添加和删除选项卡页面

问题描述 投票:1回答:2

我有一个程序,我希望每个人都有自己的选项卡,每个选项卡都是相同的,但我想删除一个选项卡,如果我需要。

private void addPerson(string name)
{
  TabPage tmp = new TabPage();
  ListView tmpList = new ListView();
  Button tmpButton = new Button();
  this.SuspendLayout();
  this.tabFrame.SuspendLayout();
  tmp.SuspendLayout();
  tmpList.SuspendLayout();
  tmpButton.SuspendLayout();
  ...
  //build the controll itself
  tmp.Controls.Add(tmpButton);
  tmp.Controls.Add(tmpList);
  tmp.Location = new System.Drawing.Point(4, 22);
  tmp.Name = name.Replace(' ', '_');
  tmp.Padding = new System.Windows.Forms.Padding(3);
  tmp.Size = new System.Drawing.Size(284, 240);
  tmp.TabIndex = 3;
  tmp.Text = name;
  tmp.UseVisualStyleBackColor = true;
  //add it to frame
  this.tabFrame.Controls.Add(tmp);
  tmpButton.ResumeLayout(true);
  tmpList.ResumeLayout(true);
  tmp.ResumeLayout(true);
  this.tabFrame.ResumeLayout(true);
  this.ResumeLayout(true);
{

名称将采用“Scott Chamberlain”的形式,因此我删除了空格并使用下划线作为名称字段。我可以添加标签,它们显示正确格式化,但是当我尝试使用代码删除标签时:

private void removePerson(string name)
{
  this.SuspendLayout();
  this.tabFrame.SuspendLayout();
  this.tabFrame.Controls.RemoveByKey(name.Replace(' ', '_'));
  this.tabFrame.ResumeLayout(true);
  this.ResumeLayout(true);
}

该选项卡不会从我的程序中消失。删除标签时我错过了什么?

c# .net visual-studio-2008 forms
2个回答
4
投票

alt text (来源:codinghorror.com

创建一个简单的TabPage与特定的Name并将其添加到ControlsTabPages作品,所以在RemoveByKeyControls上用TabPages删除它。

是否有任何代码可能会在以后更改名称?


1
投票

对于Add()和RemoveByKey()操作,请使用tabFrame.TabPages而不是tabFrame.Controls。

TabPages是一个更具指定性的控件版本,如果发生这种情况,您可以使用更专业的选项。

© www.soinside.com 2019 - 2024. All rights reserved.