我有一个添加用户按钮,可以添加文本框和按钮。我想要它,以便新按钮删除它添加的用户。我的问题是我不知道如何获得一个动态添加按钮来删除动态创建的文本框...我认为这是我如何定义变量的问题,但我不知道是什么。这就是我所拥有的:
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]);
// //}
}
答案 0 :(得分: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]);