动态创建控件 [英] Create controls dynamically

查看:99
本文介绍了动态创建控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在按下按钮之前创建控件并将其放在给定的位置。



我认为可能这样

  private TextBox txtBox = new TextBox(); 
private Button btnAdd = new Button();
private ListBox lstBox = new ListBox();
private CheckBox chkBox = new CheckBox();
private Label lblCount = new Label();

但问题在于按下按钮时,同名的控件被创建。如何避免

什么da ........
i写了,也没有例外,我期待它,因为控件已经包含 btnAdd 而不是许多按钮创建许多你想要的。
访问它们将是问题,但它将通过 @drachenstern 方法正确解决

  private void button1_Click_1(object sender,EventArgs e)
{
按钮btnAdd = new Button();

btnAdd.BackColor = Color.Gray;
btnAdd.Text =添加;
btnAdd.Location = new System.Drawing.Point(90,25 + i);
btnAdd.Size = new System.Drawing.Size(50,25);
this.Controls.Add(btnAdd);
i = i + 10;
}


解决方案

你可以尝试解决方案发布了这里。它将在构造函数中动态创建5个按钮。只需将代码移动到按钮点击事件,它应该动态添加按钮并使用单击事件注册。


I want to know if this is possible in c# winform.

create control when ever button is pressed and place it at given location.

I think it is possible like this

private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ListBox lstBox = new ListBox();
private CheckBox chkBox = new CheckBox();
private Label lblCount = new Label();

but the problem lies when ever button is pressed same name controls are created.How to avoid that

What da........ i wrote and no exception i was expecting it because control already contains btnAdd instead as many button create as many you want. Accessing them will be issue but it will be solved by @drachenstern method correct?

  private void button1_Click_1(object sender, EventArgs e)
        {
            Button btnAdd = new Button();

            btnAdd.BackColor = Color.Gray;
            btnAdd.Text = "Add";
            btnAdd.Location = new System.Drawing.Point(90, 25+i);
            btnAdd.Size = new System.Drawing.Size(50, 25);
            this.Controls.Add(btnAdd);
            i = i + 10;
        }

解决方案

You could try the solution I posted here. It will dynamically create 5 buttons in the constructor. Just move the code to the button click event and it should add the buttons dynamically and register with the Click events.

这篇关于动态创建控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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