C# 动态创建控件 很实用

代码如下。

 1 private TextBox Txt;      
2
3 protected void Page_Load(object sender, EventArgs e)
4
5 {
6
7 Create();
8
9 }
10
11 private void Create()
12
13 {
14
15 Button Btn = new Button();
16
17 Btn.ID = "MyBtn";
18
19 Btn.Text = "显示";
20
21 Btn.CommandArgument = "MyBtn";
22
23 Btn.Command += new CommandEventHandler(this.MyBtn_Command);
24
25 this.Txt = new TextBox();
26
27 this.Txt.ID = "MyTxt";
28
29 this.FindControl("form1").Controls.Add(Btn);
30
31 this.FindControl("form1").Controls.Add(Txt);
32
33 //这里还可以写成:Page.Form.Controls.Add(Txt);
34
35 }
36 36
37 37 public void MyBtn_Command(object sender, CommandEventArgs e)
38 38
39 39 {
40 40
41 41 if (e.CommandArgument.ToString() == "MyBtn")
42 42
43 43 Response.Write(Txt.Text);
44 44 }
45

web设计中,有很多场合,

页面的控件要动态创建甚至只能动态创建,将代码使用到.net的项目中。

只要灵活运用 Controls 就能获得想要的控件。

posted @ 2011-11-23 23:29  乐淘淘  阅读(1032)  评论(0编辑  收藏  举报