Home > Enterprise >  C# Dynamicaaly Add and Delete buttons
C# Dynamicaaly Add and Delete buttons

Time:01-07

From the below code, I dynamically create a list of buttons based on client names provided by a TCP connection from the clientNames[i] list.

private void updateClientListUI()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.updateClientListUI));

            }
            else
            {
                //Debug.WriteLine(clientNames[0]);
                int basex = subPanelClient.Location.X;
                int basey = subPanelClient.Location.Y;
                for (int i = 0; i < clientNames.Count; i  )
                {
                    Button b = new Button();
                    b.Left = basex;

                    b.Top = basey;
                    b.Size = new Size(25, 25); // <== add this line
                    b.Dock = DockStyle.Top;
                    b.ForeColor= Color.Gainsboro;
                    b.FlatStyle= FlatStyle.Flat;
                    b.FlatAppearance.BorderSize = 0;
                    b.Padding= new Padding(35, 0, 0, 0);
                    b.TextAlign = ContentAlignment.MiddleLeft;
                    basey  = 25;
                    b.Name = clientNames[i];
                    b.Text = clientNames[i];
                    subPanelClient.Controls.Add(b);
                    buttonsAdded.Insert(i, b);
                }

            }
        }

What I am trying to figure out, is how to delete a button (i). What I attempted is the following:

private void removingButtons(int i)
    {
        if (buttonsAdded.Count > 0)
        {
            Button buttonToRemove = buttonsAdded[i];
            subPanelClient.Controls.Remove(buttonToRemove);
            buttonsAdded.Remove(buttonToRemove);
        }
    }

Or if anyone would know how to update the current list of buttons from updateClientListUI() to the current latest list from clientNames[i] instead of a list being added onto another list.

The issue that Im getting is that obviously every time there is a connection or disconnection the list just keeps getting added instead of refreshing to the current list.

CodePudding user response:

One way to do it would be to clear the old buttons on each update.

 foreach (Button b in buttonsAdded)
 {
     subPanelClient.Controls.Add(b);    
 }
 buttonsAdded.Clear();
 for (int i = 0; i < clientNames.Count; i  )
 {
      Button b = new Button();
      ...
      ...

If the subPanelClient only contains those buttons, you could just use

subPanelClient.Controls.Clear();

Last remark: Your removingButtonk function seems to use this.Controls.Remove instead of subPanelClient.Controls.Remove.

  • Related