动态添加表单控件 [英] dynamic adding form controls
本文介绍了动态添加表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我键入下面的代码,但是我只看到一个按钮,左边有100个按钮.
i type the code below, but i only see one button in form with 100 left.
private void Form1_Load(object sender, EventArgs e)
{
Button[] btnexit = new Button[5];
for (int i = 1; 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;
}
我解决不了.
i couldn''t solve it. what is, it''s solution?
推荐答案
问题中的代码和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",这将是编程的致命罪过.
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.
上面的代码仅通过小量校正就给出了索引超出范围的异常,其工作原理如下:-
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!!
这篇关于动态添加表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文