Home > front end >  Dynamically update button
Dynamically update button

Time:01-08

I am attempting to dynamically add a list of buttons:

private void updateClientListUI()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.updateClientListUI));
            }
            else
            {
                int count = 1;
                int x = 0;
                int y = 0;
                
                for (int i = 0; i < 5; i  )
                {
                    Button btn = new Button();
                    btn.Text = count.ToString();
                    btn.Name = count.ToString();
                    btn.Size = new Size(35, 35);
                    btn.Location = new Point(150, 150 * y);
                    //btn.Dock = DockStyle.Fill;
                    y  ;
                    count  ;
                    Controls.Add(btn);
                }
                
            }
        }

Unfortunately this does not apply any buttons to the form.

In addition I was wondering how could I append these buttons in a panel called subPanelClient

CodePudding user response:

This worked for me, the issue was the position of the button, as you have to indicate it within a panel or form. In this case i just docked them to the panel

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;
                subPanelClient.Controls.Clear();
                Debug.WriteLine(clientNames.Count);

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

            }
        }
  • Related