用户定义的C#中动态创建的控件数量

时间:2013-01-28 22:48:20

标签: c# winforms dynamically-generated

我的程序目前设置为只在原始下方添加一行控件。我怎样才能使用户可以添加任意数量的控件?

private void surfaceAddButton_Click(object sender, EventArgs e)
    {           
        //Adds new set of controls on button click
        for (int i = 1; i < 2; i++)
        {

            ComboBox surfaceCombo2 = new ComboBox();
            TextBox sideWallsText2 = new TextBox();
            TextBox backWallsText2 = new TextBox();
            TextBox floorText2 = new TextBox();
            Label newLabel = new Label();
            Label newLabel2 = new Label();
            Label newLabel3 = new Label();

            Absorption_Coefficients alpha = new Absorption_Coefficients(); //Adds surfaces to combobox
            List<string> materialslist = alpha.listLoad();
            materialslist.Sort();
            surfaceCombo2.Items.AddRange(materialslist.ToArray());
            surfaceCombo2.DropDownStyle = ComboBoxStyle.DropDownList;

            //Sets locations and sizes of new row of options, then displays them
            surfaceCombo2.Location = new Point(1, 150 * i + 30);               
            sideWallsText2.Location = new Point(393, 153 * i + 30);
            backWallsText2.Location = new Point(561, 153 * i + 30);
            floorText2.Location = new Point(711, 153 * i + 30);
            newLabel.Location = new Point(321, 158 * i + 30);
            newLabel2.Location = new Point(439, 158 * i + 30);
            newLabel3.Location = new Point(609, 158 * i + 30);
            surfaceCombo2.Width = 322;
            sideWallsText2.Width = 43;
            backWallsText2.Width = 43;
            floorText2.Width = 43;
            newLabel.Text = "Side Walls, ft²";
            newLabel2.Width = 120;
            newLabel2.Text = "Back/or Front Walls, ft²";
            newLabel3.Text = "Floor/or Ceiling, ft²";

            this.Controls.Add(surfaceCombo2);
            this.Controls.Add(sideWallsText2);
            this.Controls.Add(backWallsText2);
            this.Controls.Add(floorText2);
            this.Controls.Add(newLabel);
            this.Controls.Add(newLabel2);
            this.Controls.Add(newLabel3);

            this.Size = new Size(769, 209 * i + 30); //Increases form to accomodate new controls
        }
    }

这是仅添加一个表面的表格。我希望这样做,以便每次用户点击+ Surface时都会有一个新行。

The Form with one surface added

2 个答案:

答案 0 :(得分:0)

for (int i = 1; i < 2; i++)

而不是2 in for循环,用n替换,其中n将是从某个控件收集的数字

答案 1 :(得分:0)

第一步是获取现有代码并创建一个创建行的方法。理想情况下,作为此步骤的一部分,您将创建一个自定义控件,该控件封装了您现在拥有的大部分逻辑。

第二步是采用新方法并需要参数numberOfRows,使用该参数,并将其默认为1.然后确保它仍然有效。

最后一步是为用户提供一种输入numberOfRows并将其发送到您的方法的方法。