动态创建控件 [英] dyanamically create controls

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

问题描述

朋友告诉我动态创建控件的方法

friends tell me the method to dynamically create controls

推荐答案

我在这里做了两个假设:
1.您正在使用Visual Studio.
2.这是一个Winforms项目.

一种简单的方法(尽管有点笨拙)是在设计时创建所需的控件,然后将在"designer"类中生成的代码复制并粘贴到将在运行时调用的方法中.然后只需从可视设计器中删除控件即可.
I''m making a couple of assumptions here:
1. You''re using Visual Studio.
2. This is a Winforms project.

One simple, albeit slightly hacky, way is to create the controls you want at design time and copy and paste the code generated in the "designer" classes into a method you will call at run time. Then just delete the controls from visual designer.


创建控件并将其添加到父容器中.
Create the control and add it to parent container..

TextBox tb = new TextBox();

panel.Controls.Add(tb);




您还应该将控件的属性设置为正确放置.

干杯
:cool:




You should also need to set properties to the control to position it correctly.

Cheers
:cool:


DropDownList ddlday = new DropDownList();
DropDownList ddlmonth = new DropDownList();
DropDownList dllyear = new DropDownList();
Button btn = new Button();
标签lbl = new Label();
lbl.ID ="lbl";
lbl.Text =日期";
dllyear.ID ="ddlyear";
ddlmonth.ID ="ddlmonth";
ddlday.ID ="ddlday";
btn.ID ="btnsave";
btn.Text =保存";
for(int i = 1; i< 32; i ++)
{
ddlday.Items.Add(i.ToString());
}
for(int i = 1; i< 13; i ++)
{
ddlmonth.Items.Add(i.ToString());
}
for(int i = System.DateTime.Now.Year-20; i< System.DateTime.Now.Year + 1; i ++)
{
dllyear.Items.Add(i.ToString());
}

Panel1.Controls.Add(ddlday);
Panel1.Controls.Add(ddlmonth);
Panel1.Controls.Add(dllyear);
btn.Click + =新的EventHandler(btnsave_Click);
Panel1.Controls.Add(btn);
DropDownList ddlday = new DropDownList();
DropDownList ddlmonth = new DropDownList();
DropDownList dllyear = new DropDownList();
Button btn = new Button();
Label lbl = new Label();
lbl.ID = "lbl";
lbl.Text = "date";
dllyear.ID = "ddlyear";
ddlmonth.ID = "ddlmonth";
ddlday.ID = "ddlday";
btn.ID = "btnsave";
btn.Text = "Save";
for (int i = 1; i < 32; i++)
{
ddlday.Items.Add(i.ToString());
}
for (int i = 1; i < 13; i++)
{
ddlmonth.Items.Add(i.ToString());
}
for (int i = System.DateTime.Now.Year - 20; i < System.DateTime.Now.Year + 1; i++)
{
dllyear.Items.Add(i.ToString());
}

Panel1.Controls.Add(ddlday);
Panel1.Controls.Add(ddlmonth);
Panel1.Controls.Add(dllyear);
btn.Click += new EventHandler(btnsave_Click);
Panel1.Controls.Add(btn);


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

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