2017-06-22 124 views
-1

我有一个添加用户按钮,它添加了一个文本框和一个按钮。我需要它,以便新按钮删除它添加的用户。我的问题是我不知道如何获得动态添加的按钮来删除动态创建的文本框......我认为它是如何定义变量的问题,但我不知道是什么。下面是我有:删除动态创建的文本框

private void AddUserbtn_Click_1(object sender, EventArgs e) 
    { 
     TextBox[] Alias = new TextBox[n]; 

     Button[] Remove = new Button[n]; 

     int AliasX, AliasY, RemoveX, RemoveY; 

     AliasX = 40; 
     AliasY = 45; 

     RemoveX = 946; 
     RemoveY = 45; 


     for (int i = 0; i < n; i++) 
     { 
      Alias[i] = new TextBox(); 
      Alias[i].Size = new Size(233, 26); 
      Alias[i].Location = new Point(AliasX, AliasY + space); 
      Alias[i].Font = new Font("Arial", 10); 

      Remove[i] = new Button(); 
      Remove[i].Location = new Point(RemoveX, RemoveY + space); 
      Remove[i].Text = ""; 
      Remove[i].Font = new Font("Arial", 10); 
      Remove[i].FlatStyle = FlatStyle.Flat; 
      Remove[i].BackgroundImage =Properties.Resources.btn_remove_user; 
      Remove[i].FlatAppearance.BorderColor = Color.White; 
      Remove[i].BackgroundImageLayout = ImageLayout.Center; 
      Remove[i].Size = new Size(95, 23); 
      Remove[i].UseVisualStyleBackColor = true; 
      Remove[i].Click += new EventHandler(Remove_Click); 

      space += 35; 
     } 


     for (int i = 0; i < n; i++) 
     { 
      Panel.Controls.Add(Alias[i]); 

     } 

     //for(int i=0; i <n;i++) 
     //Remove[i].Click += delegate 
     //{ 
     // Panel.Controls.Remove(Alias[i]); 
     //}; 



    } 

    private void Remove_Click(object sender, EventArgs e) 
    { 
     // Button Remove = sender as Button; 

     // //TextBox[] Alias = new TextBox[n]; 
     // //for (int i = 0; i <n; i++) 
     // //{ 
     // // Panel.Controls.Remove(Alias[i]); 



     // //} 
    } 
+1

将Id属性设置为您的控件,以及如何知道要删除的控件?我认为你需要在你的问题中添加更多信息。 –

+1

TextBox和Button应该可能位于UserControl中。 – LarsTech

+0

当我点击删除按钮删除按钮和别名文本框应该删除 – Julie

回答

1

给你的对象有意义的名称,如:

Alias[i].Name = "UserTextBox" + i; 
Remove[i].Name = "UserButton" + i; 

这样你可以找对象被排除。

Panel.Controls.Remove(Panel.Controls["UserTextBox" + i]); 
Panel.Controls.Remove(Panel.Controls["UserButton" + i]); 
+0

工作谢谢你! – Julie