在点击事件上添加控件 [英] Add controls on click event

查看:69
本文介绍了在点击事件上添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我要添加控件的代码.它有效,但仅适用于第一次点击..

Below is my code to add control. it works but only for 1st click..

int x=27, z=65;
        private void button1_Click(object sender, EventArgs e)
        {
            TextBox textBox2 = new TextBox();
            textBox2.Name = "textBox2";
            textBox2.Location = new Point(x,z+25);
            textBox2.Visible = true;
            this.Controls.Add(textBox2);
        }


我想使用相同的click事件将多个文本框添加到表单中..
在此先感谢


I want to add multiple text box to my form using same click event..
thanks in advance

推荐答案

hii,
只是
将z + 25更改为z + = 25并全局定义x和z,它将成功运行.

修改后的代码

hii,
just
change z+25 to z+=25 and define x and z globally it will run successfully.

modified code

public partial class Form1 : Form
   {
       int x = 27, z = 65;
       public Form1()
       {
           InitializeComponent();
       }
       private void button1_Click(object sender, EventArgs e)
       {
           TextBox textBox2 = new TextBox();
           textBox2.Name = "textBox2";
           textBox2.Location = new Point(x, z += 25);
           textBox2.Visible = true;
           this.Controls.Add(textBox2);
       }
   }


您是否听说过循环?
Have you heard about loops?
int i = 1, x=27, y=65;
for (i = 0; i < 5; i++ )
{
  TextBox tb = new TextBox();
  tb.Name = "textBox" + i.ToString();
  tb.Location = new Point(x, y + 25 * i);
  tb.Visible = true;
  this.Controls.Add(tb);
}



看到下面的代码:
Hi,
See you code below:
int x=27, z=65;
private void button1_Click(object sender, EventArgs e)
{
    TextBox textBox2 = new TextBox();
    textBox2.Name = "textBox2";
    textBox2.Location = new Point(x,z+25);
    textBox2.Visible = true;
    this.Controls.Add(textBox2);
}


您正在动态添加代码,正确.您的问题是,您一次又一次地将控件添加到同一位置.每次添加时,请尝试为按钮放置不同的位置.试试这个:


You are adding the code dynamically, correct. Your problem is, you are adding the controls in the same location again and again. Try putting the different location for the buttons each time you are adding. Try this:

int x=27, z=65;
private void button1_Click(object sender, EventArgs e)
{
    TextBox textBox2 = new TextBox();
    textBox2.Name = "textBox2";
    textBox2.Location = new Point(x,z+25);
    textBox2.Visible = true;
    this.Controls.Add(textBox2);
    z += 20;
    y += 20;
}




希望对您有所帮助.
--Amit




Hope it helps.
--Amit


这篇关于在点击事件上添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆