在aspx網頁裡動態載入UserControl,並且透過UserControl Event的訂閱,來取得對應的值
最近在小舖裡看到了這方面的問題....
小弟找了很多的資料..做一個範例介紹如何動態載入User Control
與如何透過aspx網頁訂閱User Control的Event,來取得相關的資訊
此範例先做一個檔案上傳的User Control,當網頁需要用到上傳功能時..
就可以將此控項制拉進來,,或用動態載入的方式來載入此控制項
所以此範例將會出現兩個User Control(一個是用拉的,一個是動態載入的)
當使用者選取好檔案,按upload時,aspx網頁就可以取得user control傳過來的檔案資訊
這樣一來以後就不用重覆寫上傳檔案的程式了,,只要拉一個user control就可以快速讓網頁有上傳的功能了
c#範例
User Control
WebUserControl.ascx
2 <asp:fileupload id="FileUpload1" runat="server" />
3 <asp:button id="btnUpload" runat="server" onclick="btnUpload_Click" text="upload" />
4
WebUserControl.ascx.cs

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20 public string FileName
21

22

23

24

25

26 public int FileSize
27

28

29

30

31

32

33

34 public delegate void MyClick(object sender, MyEventArgs e);
35

36 public event MyClick cClick;
37

38 private void WebUserControl_Click(object sender, MyEventArgs e)
39

40

41

42

43

44

45

46 protected void Page_Load(object sender, EventArgs e)
47

48

49

50

51

52

53

54 EventArgs.FileName = this.FileUpload1.FileName;
55

56

57

58

59 WebUserControl_Click(this, EventArgs);
60

61

62

aspx網頁
UserControl.aspx
02
03 <%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07 <title>UserControl</title>
08 </head>
09 <body>
10 <form id="form1" runat="server">
11 <div>
12 <uc1:WebUserControl ID="WebUserControl1" OncClick="WebUserControl1_cClick" runat="server" />
13 </div>
14 </form>
15 </body>
16 </html>
17
UserControl.aspx.cs

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22 //動態加入UserControl的事件
23

24

25

26

27

28 protected void Page_Load(object sender, EventArgs e)
29

30

31

32

33 //事先拉好的UserControl事件
34

35

36

37

38

39

執行結果:
參考網址:
http://www.thescripts.com/forum/thread232638.html
http://blog.blueshop.com.tw/jeff377/archive/2008/01/19/54090.aspx
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080224205358PAU&fumcde=FUM20041006161839LRJ&rplcnt=4
http://blog.xuite.net/cct0201/derek/15360068