简体   繁体   中英

Auto arrange unlimited number of buttons on form

I'm trying generate dynamically a bunch of buttons. The number of buttons is determined by how many pits are alive, and this is retrieved from a database.

Here is how it looks like :

纽扣

Here is what I used to generate them :

private void Form1_Load(object sender, EventArgs e)
{
    int numOf = pits.numOfPits();
    Button[] genButtons = new Button[numOf];
    int l = 1;
    for (int i = 0; i < numOf; i++)
    {

        genButtons[i] = new Button();
        genButtons[i].Width = 160;
        genButtons[i].Height = 80;
        Point location = new Point((i + 1) *200,75);

        if (location.X > this.ClientSize.Width - 200)
        {
            location.X = l * 200;
            location.Y += 100;
                l++;
        }
        genButtons[i].Location = location;  
        this.Controls.Add(genButtons[i]);
    }
}

The problem is that it will only work for 2 rows and it is kind of hard coded. How can I improve it to support an unlimited number of buttons.

You can ignore the limited "height" of form for the purpose of this question. I'll probably add some pagination later.

Add button controls to the FlowLayoutPanel . Extend the FlowLayoutPanel to include items per page, current page, and data to implement paging.

private void Form1_Load(object sender, EventArgs e)
{
    FlowLayoutPanel flp = new FlowLayoutPanel();
    for (int i = 0; i < pits.numOfPits(); ++i)
    {
        Button btn = new Button();
        btn.Width = 160;
        btn..Height = 80; //set padding or margin to appropriate values
        flp.Controls.Add(btn);
    }
    this.Controls.Add(flp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM