Search code examples
c#winformsradio-buttondynamic-controls

Dynamic creating radiobuttons and arange them inside form


I'm creating dynamically N radio buttons on form on this way:

 private void CreateRadioButton()
    {
        int rbCount = 40;

        System.Windows.Forms.RadioButton[] radioButtons = new System.Windows.Forms.RadioButton[rbCount];

        for (int i = 0; i < rbCount; ++i)
        {
            radioButtons[i] = new RadioButton();
            radioButtons[i].Text = Convert.ToString(i);
            int x = 514 + i*37;
            int y = 20;
            radioButtons[i].Location = new System.Drawing.Point(x,y);
            radioButtons[i].Size = new Size(37, 17);
            this.Controls.Add(radioButtons[i]);
        }
    }

In this case the radiobuttons are all created in one row but i need to arrange them in multiple rows inside specific region. Is it possible? What approach to use for this kind of problem?


Solution

  • If you want to fix your code without the suggested ways in the comments

    private void CreateRadioButton()
    {
        int rbCount = 40;
            int numberOfColumns = 8;
            var radioButtons = new RadioButton[rbCount];
            int y = 20;
            for (int i = 0; i < rbCount; ++i)
            {
                radioButtons[i] = new RadioButton();
                radioButtons[i].Text = Convert.ToString(i);
                if (i%numberOfColumns==0)  y += 20; 
                var x = 514 + i%numberOfColumns * 37;
                radioButtons[i].Location = new Point(x, y);
                radioButtons[i].Size = new Size(37, 17);
                this.Controls.Add(radioButtons[i]);
            }
    }