Creating a dynamic button and placing them in a predefined order using C #

NET 4.5 C # to create a window shape. I want to dynamically create and add buttons, and assign click events to them, but I want them to be dynamically placed in a certain way, like an image.

enter image description here

My question is how to place buttons dynamically in the way described above, i.e. 4x4 format (4 buttons per row, 4 columns, but unlimited rows). Can this be done in the form of a win?

I am currently trying to use the code below, but have no clear idea of ​​how I can put the buttons as shown above.

        public Form1()
    {
        InitializeComponent();

        for (int i = 0; i < 5; i++)
        {
            Button button = new Button();
            button.Location = new Point(160, 30 * i + 10);
            button.Click += new EventHandler(ButtonClickCommonEvent);
            button.Tag = i;
            this.Controls.Add(button);
        }
    }

void ButtonClickCommonEvent(object sender, EventArgs e)
  {
     Button button = sender as Button;
     if (button != null)
     {       
        switch ((int)button.Tag)
        {
           case 0:
              // First Button Clicked
              break;
           case 1:
              // Second Button Clicked
              break;
           // ...
        }
     }
  }

Please advise the solution with the codes.

+3
1

TableLayoutPanel, .

:

private void Form1_Load(object sender, EventArgs e)
{
    var rowCount = 3;
    var columnCount = 4;

    this.tableLayoutPanel1.ColumnCount = columnCount;
    this.tableLayoutPanel1.RowCount = rowCount;

    this.tableLayoutPanel1.ColumnStyles.Clear();
    this.tableLayoutPanel1.RowStyles.Clear();

    for (int i = 0; i < columnCount; i++)
    {
        this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100 / columnCount));
    }
    for (int i = 0; i < rowCount; i++)
    {
        this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100 / rowCount));
    }

    for (int i = 0; i < rowCount* columnCount; i++)
    {
        var b = new Button();
        b.Text = (i+1).ToString();
        b.Name = string.Format("b_{0}", i + 1);
        b.Click += b_Click;
        b.Dock = DockStyle.Fill;
        this.tableLayoutPanel1.Controls.Add(b);
    }
}

void b_Click(object sender, EventArgs e)
{
    var b = sender as Button;
    if (b != null)
        MessageBox.Show(string.Format("{0} Clicked", b.Text));
}

enter image description here

:

+6

Source: https://habr.com/ru/post/1655943/


All Articles