簡體   English   中英

如何在c#中刪除表單控件?

[英]How to remove form control in c#?

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控件。

嘗試這個

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;
         }
     }
}

我認為這里的問題是每次輸入方法時都會創建一個新的 TextBox。 移動你的TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); 在方法之外,我認為它會工作得很好。

您總是創建一個新實例,因此您的局部變量中沒有正確的實例。

這是一種方法:

  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);
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM