ASP.NET中动态加载用户控件并传值
ASP.NET 页面:在此页面动态调用用户控件(.ASCX)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div id="info_1">
<asp:PlaceHolder runat="server" ID="phCourseware"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
ASP.NET 后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TabLoadControls();
}
#region 加载控件
private void TabLoadControls(int iChapterId, int iCourseID)
{
/*
* 第一种方法:这种方法能传值
* 这种写法需要在前台页面中拖拽控件ChapterCourseware.ascx,也就是在Default.aspx页面中加入这行代码:
* <%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
*/
//清楚容器控件中的控件
//phCourseware.Controls.Clear();
ASP.teachercenter_controls_chaptercourseware_ascx ucCourseware = new ASP.teachercenter_controls_chaptercourseware_ascx();
//给用户控件传值
ucCourseware.ChapterId = iChapterId;
ucCourseware.CourseID = iCourseID;
//加载用户控件至容器控件中
phCourseware.Controls.Add(ucCourseware);
/*
* 第二种,不需要传值的写法
* 这种写法不需要在前台页面中拖拽控件ChapterCourseware.ascx,也就是在Default.aspx页面中不需要这行代码:
* <%@ Register Src="ChapterCourseware.ascx" TagName="ChapterCourseware" TagPrefix="uc2" %>
*
*/
phCourseware.Controls.Add(TemplateControl.LoadControl("~/ChapterCourseware.ascx"));
}
#endregion
}
ChapterCourseware.ascx 控件的后台代码中写入属性以用于接收参数:
#region 页面参数 课程ID:CourseID 章节ID:ChapterId
/// <summary>
/// 课程ID
/// </summary>
public int CourseID
{
get
{
return (int)ViewState["CourseID"];
}
set
{
ViewState["CourseID"] = value;
}
}
/// <summary>
/// 章节ID
/// </summary>
public int ChapterId
{
get
{
if (ViewState["ChapterId"] != null)
return Convert.ToInt32(ViewState["ChapterId"]);
else
return -1;
}
set
{
ViewState["ChapterId"] = value;
}
}
#endregion