直接把前一个按钮对象保存在当前按钮的Tag属性里面:
private void Form2_Load(object sender, EventArgs e)
{
Button btn1=null;//前一个按钮
for(int i=1;i<21;i++){
Button btn = new Button();
btn.Text = "button" + i;
btn.Name = "button" + i;
btn.Click += new EventHandler(btn_Click);
btn.Size = new System.Drawing.Size(80,20);
btn.Tag = btn1;
btn.Location = new Point(i * 30, i * 20);
this.Controls.Add(btn);
btn1 = btn;
}
}
void btn_Click(object sender, EventArgs e) {
Button btn = sender as Button;
MessageBox.Show(btn.Name.ToString());
if (btn.Tag != null)
{
//弹出前一个按钮的位置信息
Button btn1 = btn.Tag as Button;
MessageBox.Show("X:"+btn1.Location.X +" Y:"+ btn1.Location.X);
}
}
这是部分代码还是原始的,如果是原始的,这里面问题就比较多,一般的写法
for(int i=0;i{
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
btn.Size = new System.Drawing.Size(20,20);
btn.Tag=i;
btn.Location = new Point((i+1)*30, (i+1)*20);
his.Controls.Add(btn);
btnlist[i]=btn;
}
Button[] btnlist=new Button[20];
void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
int i=(int)btn.Tag;//得到序号,前一按钮为i-1
if(i>0)
{
MessBox.Show("前一按钮为"+(i-1));
//btnlist[i-1].Location即为前一按钮的位置
}
}
for(int i=1;i<21;i++){
Button btn = new Button();
btn.Click += new EventHandler(btnXXX_Click);
btn.Size = new System.Drawing.Size(90,20);
btn.Tag = i;
btn.Text = "Btn"+i;
btn.Name = "btn"+i;
btn.Location = new Point(23, i*20);
this.Controls.Add(btn);
}
void btnXXX_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
int tag = Convert.ToInt32(btn.Tag);
tag=tag==1?1:tag-1;
Button btnPrev = this.Controls["btn" + tag] as Button;
MessageBox.Show(btnPrev.Text);
}
你的location是规则生成的,每个按钮都是x相差30的倍数,y相差20的倍数。前一个button的按钮的坐标=本身按钮的x-30,y-20
你new button的时候,多一行
btn.name = "xx"+i.ToString();
你不就知道编号了么