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

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

问题描述

我想知道这是否可能在C#中的winform。



当按下曾经按钮创建控制,并将其放置在指定位置。



我认为这是可能是这样

 私人文本框txtBox =新的TextBox(); 
私人按钮btnAdd =新按钮();
私人列表框lstBox =新的ListBox();
私人复选框chkBox =新的复选框();
私人标签lblCount =新的Label();



但问题在于当按下按钮过同名控制是created.How避免




I写什么大........没有例外,我期待它,因为控制已包含 btnAdd 而不是尽可能多的按钮来创建你想要的。
访问他们的将是问题,但它将被 @drachenstern 解决方法正确吗?



 私人无效button1_Click_1(对象发件人,EventArgs五)
{
键btnAdd =新按钮();

btnAdd.BackColor = Color.Gray;
btnAdd.Text =添加;
btnAdd.Location =新System.Drawing.Point(90,25 + I);
btnAdd.Size =新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天全站免登陆