如对 动态增加 控件 没概念的人,请参阅 ASP.NET 动态加载控件 基础篇
这篇来示范,动态增加页面控件并设定回传事件,在事件中 取得 动态增加的控件中输入的值
如此 做法的动态控件,请注意 需要在 Init or Load 事件中来增加,如此 ASP.NET 的 ViewState 才能正确设定相对控件的参数
1 <%@ Page Language="C#" AutoEventWireup="True" %>
2
3 <script language="C#" runat=server>
4 public void Page_Init(object sender, System.EventArgs e)
5 {
6 Label message = new Label();
7 message.ID = "请输入你要说的话";
8 sourceTag.Controls.Add(message);
9
10 TextBox input = new TextBox();
11 input.ID = "input";
12 sourceTag.Controls.Add(input);
13
14 Button btnSayHello = new Button();
15 btnSayHello.ID = "btnSayHello";
16 btnSayHello.Text = "SayHello";
17 btnSayHello.Click += new EventHandler(SubmitBtn_Click);
18 sourceTag.Controls.Add(btnSayHello);
19 }
20
21 void SubmitBtn_Click(Object sender, EventArgs e)
22 {
23 TextBox input = (TextBox)sourceTag.FindControl("input");
24 LiteralControl lc;
25 lc = new LiteralControl("<H3>" + input.Text + "</H3>");
26 sourceTag.Controls.Add(lc);
27 }
28
29 </script>
30 <html>
31 <head>
32 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
33 </head>
34 <body>
35 <form runat="server">
36
37 <h3>动态增加控件 Event 篇</h3>
38
39 <p/>
40 <div id="sourceTag" runat="server">
41 </div>
42 <p/>
43 一条小龙
44 </form>
45 </body>
46 </html>