Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - Removing dynamically created textboxes

I have an add user button which adds a textbox and a button. I want it so that the new button removes the user it added. My problem is I don't know how to get a dynamically added button to delete dynamically created textboxes... I think its a problem with how I defined the variables but I don't know what . Here's what I have:

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



        //    //}
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Give your objects meaningful names like:

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

This way you can find the object to be excluded.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...