ASP.NET 页面:在此页面动态调用用户控件(.ASCX)

 1 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 2 
 3 <%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
 4 
 5 <head runat="server">
 6     <title>无标题页</title>
 7 </head>
 8 <body>
 9     <form id="form1" runat="server">
10     <div id="info_1">
11         <asp:PlaceHolder runat="server" ID="phCourseware"></asp:PlaceHolder>
12     </div>
13     </form>
14 </body>
15 </html>

ASP.NET 后台代码:

 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Web;
 5 using System.Web.Security;
 6 using System.Web.UI;
 7 using System.Web.UI.WebControls;
 8 using System.Web.UI.WebControls.WebParts;
 9 using System.Web.UI.HtmlControls;
10 
11 public partial class _Default : System.Web.UI.Page 
12 {
13     protected void Page_Load(object sender, EventArgs e)
14     {
15         TabLoadControls();
16     }
17 
18 
19     #region 加载控件
20     private void TabLoadControls(int iChapterId, int iCourseID)
21     {
22         /*
23          *  第一种方法:这种方法能传值
24          *  这种写法需要在前台页面中拖拽控件ChapterCourseware.ascx,也就是在Default.aspx页面中加入这行代码:
25          * <%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
26          */
27         //清楚容器控件中的控件
28         //phCourseware.Controls.Clear();
29 
30         ASP.teachercenter_controls_chaptercourseware_ascx ucCourseware = new ASP.teachercenter_controls_chaptercourseware_ascx();
31         //给用户控件传值
32         ucCourseware.ChapterId = iChapterId;
33         ucCourseware.CourseID = iCourseID;
34         //加载用户控件至容器控件中
35         phCourseware.Controls.Add(ucCourseware);
36 
37 
38 
39         /*  
40          *  第二种,不需要传值的写法
41          *  这种写法不需要在前台页面中拖拽控件ChapterCourseware.ascx,也就是在Default.aspx页面中不需要这行代码:
42          * <%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
43          * 
44         */
45 
46         phCourseware.Controls.Add(TemplateControl.LoadControl("~/ChapterCourseware.ascx"));
47     }
48     #endregion
49 }

ChapterCourseware.ascx 控件的后台代码中写入属性以用于接收参数:

 1 #region 页面参数  课程ID:CourseID  章节ID:ChapterId
 2     /// <summary>
 3     /// 课程ID
 4     /// </summary>
 5     public int CourseID
 6     {
 7         get
 8         {
 9             return (int)ViewState["CourseID"];
10         }
11         set
12         {
13             ViewState["CourseID"] = value;
14         }
15     }
16 
17     /// <summary>
18     /// 章节ID
19     /// </summary>
20     public int ChapterId
21     {
22         get
23         {
24             if (ViewState["ChapterId"] != null)
25                 return Convert.ToInt32(ViewState["ChapterId"]);
26             else
27                 return -1;
28         }
29         set
30         {
31             ViewState["ChapterId"] = value;
32         }
33     }
34     #endregion

 

 



posted @ 2012-05-15 13:44  简单的执着_俊  阅读(937)  评论(0编辑  收藏  举报