且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加表单控件

更新时间:2022-04-30 03:46:37

问题中的代码和Mantu的答案都是错误的.应该是这样的:
Both code in the question and the answer by Mantu are wrong. It should be something like that:
int buttonCount = 5;
Button[] buttons = new Button[buttonCount];

//...

int gap = 10; //... some suitable gap between buttons
int currentX = //... some starting position
for (int index = 0; index < buttonCount; ++index) {
    Button button = new Button();
    button.Text = //... and not this.Text, why?
    button.Top = //...  
    button.Left = currentX + gap;
    buttons[index] = button;
    this.Controls.Add(button);
    currentX += this.Width;
}


这样,您可以在设置完文本时考虑到按钮的实际宽度,按X排列这些按钮.另外,请注意,我没有在任何地方重复"5",这将是编程的致命罪过.

—SA


This way, you can arrange those buttons by X taking into account their actual width when the text is already set up. Also, pay attention that I did not repeat your "5" anywhere, which would be a deadly sin of programming.

—SA


上面的代码仅通过小量校正就给出了索引超出范围的异常,其工作原理如下:-


The above code gives index out of bound exception just alittle correction and it works as below:-


Button[] btnexit = new Button[5];
           for (int i = 0; i < 5; i++)
           {
               btnexit[i] = new Button();
               this.Controls.Add(btnexit[i]);
               this.Text = this.Text + i.ToString();
           }
           btnexit[1].Left = 100;
           btnexit[2].Left = 200;
           btnexit[3].Left = 300;
           btnexit[4].Left = 400;




祝你好运!




Best of luck!!