如何在c#中删除表单控件?

时间:2016-05-03 07:36:48

标签: c# forms controls

TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();

if (Cat0.Text == "test")
{
    txt1.Name = "testText";
    txt1.Width = 170;
    txt1.Height = 21;
    txt1.Location = new System.Drawing.Point(122, 145);

    txt2.Name = "testText2";
    txt2.Width = 170;
    txt2.Height = 21;
    txt2.Location = new System.Drawing.Point(122, 171);

    panel1.Controls.Add(txt1);
    panel1.Controls.Add(txt2);
}
else
{
    if (panel1.Controls.Contains(txt1)) // not working
    {
        panel1.Controls.Remove(txt1);
    }
}

if else语句不起作用。所以我无法删除此块中的表单控件。我认为不工作的原因是因为使用代码创建了txt1控件。

3 个答案:

答案 0 :(得分:0)

试试这个

TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
if (Cat0.Text == "test")
{
     txt1.Name = "testText";
     txt1.Width = 170;
     txt1.Height = 21;
     txt1.Location = new System.Drawing.Point(122, 145);
     txt2.Name = "testText2";
     txt2.Width = 170;
     txt2.Height = 21;
     txt2.Location = new System.Drawing.Point(122, 171);
     panel1.Controls.Add(txt1);
     panel1.Controls.Add(txt2);
}
else
{
     foreach (Control item in panel1.Controls)
     {
         if (item.Name == "testText")
         {
              panel1.Controls.Remove(item);
              break;
         }
     }
}

答案 1 :(得分:0)

我认为这里的问题是每次输入方法时都要创建一个新的TextBox。将TextBox txt1 = new TextBox();TextBox txt2 = new TextBox();移到方法之外,我认为它会正常工作。

答案 2 :(得分:0)

您始终创建一个新实例,因此您的本地变量中没有正确的实例。

这是一种方法:

  TextBox txt1 = null;

  //Lookup txt1
  foreach (Control item in panel1.Controls)
  {
    if (item.Name == "testText")
    {
      txt1 = (TextBox)item;
    }
  }      

  TextBox txt2 = null;
  //Lookup txt2
  foreach (Control item in panel1.Controls)
  {
    if (item.Name == "testText2")
    {
      txt2 = (TextBox)item;
    }
  }
  if (Cat0.Text == "test")
  {
    if (txt1 == null)
    {
      //only if txt1 not found add it
      txt1 = new TextBox();
      txt1.Name = "testText";
      txt1.Width = 170;
      txt1.Height = 21;
      txt1.Location = new System.Drawing.Point(122, 145);
      panel1.Controls.Add(txt1);
    }

    if (txt2 == null)
    {
      txt2 = new TextBox();
      txt2.Name = "testText2";
      txt2.Width = 170;
      txt2.Height = 21;
      txt2.Location = new System.Drawing.Point(122, 171);
      panel1.Controls.Add(txt2);
    }
  }
  else
  {
    if (panel1.Controls.Contains(txt1))
    {
      panel1.Controls.Remove(txt1);
    }
  }
}