我有一个Windows窗体应用程序,我正在尝试添加按钮来模仿计算器。
public class myform : Form
{
public myform()
{
//setting size of form
this.Text = "Calculator";
this.Height = 600;
this.Width = 400;
//creating buttons from 0-9
Button[] b = new Button[10];
int x = 0;
int y = 0;
string ch;
for (int i = 0; i < b.Length; i++)
{
ch = Convert.ToString(i);
x = 0;
y = y + 50;
b[i] = new Button();
b[i].Height = 40;
b[i].Width = 40;
b[i].Text = ch;
for (int j = 0; j < 3; j++)
{
x = x + 50;
b[i].Location = new Point(x, y);
}
}
for (int i = 0; i < b.Length; i++)
{
this.Controls.Add(b[i]);
}
}
}
这里是我正在创建上述myform类对象的表单类。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myform mf = new myform();
mf.Show();
}
}
答案 0 :(得分:0)
问题似乎是你总是将x值设置为x = x + 150;我建议你把你的x值改为x =(i%3)* 50;你的y到y =(i / 3)* 50; 应该为你提供一系列漂亮的按钮。
ch = Convert.ToString(i);
x = (i%3)*50;
y = (i/3)*50;
b[i] = new Button();
b[i].Height = 40;
b[i].Width = 40;
b[i].Text = ch;
b[i].Location = new Point(x, y);
将是你的新循环体。