'How to create an array of buttons and set them to do a similar job?

I have 250 buttons to make and instead of copying and pasting 250 times, I want to create an array of buttons and then set each of them to display, example, a number from an array of numbers (1 to 250) to a text box.

E.g: press btn1 the text box displays "1", press btn7 the text box displays "7", press btn250 the text box displays "250" and so on.

(this is just an example, I don't need them to display numbers, I need them to do something else that does involve arrays)



Solution 1:[1]

The following class will create any amount of buttons best done on a FlowLayoutPanel.

public class ControlHelper
{
    public static List<Button> ButtonsList { get; set; }
    public static int Top { get; set; }
    public static int Left { get; set; }
    public static int Width { get; set; }
    public static int HeightPadding { get; set; }
    public static string BaseName { get; set; } = "Button";
    public static Control ParentControl { get; set; }
    public static int Index = 0;
    public delegate void OnClick(object sender);
    public static event OnClick ButtonClick;

    public static void Initialize(Control pControl, int top, int heightPadding, int left, int width)
    {
        ParentControl = pControl;
        Top = top;
        HeightPadding = heightPadding;
        Left = left;
        Width = width;
        ButtonsList = new List<Button>();
    }

    public static void CreateButton()
    {

        var button = new Button()
        {
            Name = $"{BaseName}{Index +1}",
            Width = Width,
            Location = new Point(Left, Top),
            Parent = ParentControl,
            Visible = true,
            Tag = Index +1
        };

        button.Click += (sender, args) => ButtonClick?.Invoke(sender);
            
        ButtonsList.Add(button);

        ParentControl.Controls.Add(button);
        Top += HeightPadding;
        Index += 1;

    }

}

Example usage with a FlowLayoutPanel docked to the form, a Panel at bottom of form with a TextBox.

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();

        ControlHelper.ButtonClick += OnButtonClick;
        ControlHelper.Initialize(flowLayoutPanel1, 20, 30, 10, 50);

        for (int index = 0; index < 250; index++)
        {
            ControlHelper.CreateButton();
        }

    }

    private void OnButtonClick(object sender)
    {
        textBox1.Text = ((Button)sender).Tag.ToString();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karen Payne