如何使用点类在 c# 上动态添加多个按钮

本文关键字:添加 动态 按钮 何使用 | 更新日期: 2023-09-27 18:31:55

您好,我尝试在表单面板上添加多个按钮并彼此相邻,但它将它们放在彼此之上。我正在使用以下功能。守则:

    private void CreatBtn()
    {
        Point[] p = new Point[6];
        string log = "";
       Form2 frm2 = new Form2();
        Button[] btn = new Button[6];
        for (int i = 0; i < btn.GetLength(0); i++)
        {
                btn[i] = new Button();
                btn[i].Height = 65;
                btn[i].Width = 80;
                p[i] = new Point();
                p[i].X = i * 83;
                p[i].Y =0;
                log +=p.ToString() +"'n";
                btn[i].PointToClient(p[i]);
                btn[i].Show();         
        }
        panel1.Controls.AddRange(btn);
    }

如何使用点类在 c# 上动态添加多个按钮

为按钮添加Left

btn[i] = new Button();
btn[i].Height = 65;
btn[i].Width = 80;
btn[i].Left = i * 83; //Now they'll be next to each other.

您也可以考虑使用FlowLayoutPanel

在它的面板中使用 flowLayoutPanel 将但彼此相邻,直到按钮到达它的末尾,然后它将创建一个新的原始

 Point[] p = new Point[6];
        string log = "";

        Button[] btn = new Button[6];
        for (int i = 0; i < btn.GetLength(0); i++)
        {
            btn[i] = new Button();
            btn[i].Height = 65;
            btn[i].Width = 80;
            p[i] = new Point();
            p[i].X = i * 83;
            p[i].Y = 0;
            log += p.ToString() + "'n";
            btn[i].PointToClient(p[i]);
            btn[i].Show();
        }
        FlowLayoutPanel pan = new FlowLayoutPanel();
        pan.Width=500;//width of all buttons
        pan.Height = 100;
        pan.Controls.AddRange(btn);
        panel1.Controls.Add(pan);