动态加载用户控件及获取用户控件暴露的属性值
using UnleashedUI.Ch7.UserControls; //引用用户控件所在的文件夹
private Control _survey = null;
//通过DropDownList选择不同的用户控件,在PlaceHolder控件中呈现
protected void Page_Load(object sender, EventArgs e)
{
switch (ddlSelect.SelectedIndex)
{
//这里的"UserControls/ASPSurvey.ascx"路径是相对于呈现它的页面的
case 1: _survey = Page.LoadControl("UserControls/ASPSurvey.ascx");
break;
case 2: _survey = Page.LoadControl("UserControls/ASPNETSurvey.ascx");
break;
default:
break;
}
if (_survey!=null)
{
PlaceHolder1.Controls.Add(_survey);
}
}
//点击提交按钮之后,将用户控件中暴露的属性呈现在Literal控件中
protected void btnSubmit_Click1(object sender, EventArgs e)
{
switch (ddlSelect.SelectedIndex)
{
case 1:
//转换为相应的用户控件,以便提取它的属性
ASPSurvey aspResults = (ASPSurvey)_survey;
ltlResult.Text = "<h1>ASP Survey</h1>";
ltlResult.Text += "<br/>Know slow?" + aspResults.KnowSlow;
ltlResult.Text += "<br/>Know outdated?"+aspResults.KnowOutdated;
break;
case 2:
ASPNETSurvey aspNetResults = (ASPNETSurvey)_survey;
ltlResult.Text = "<h1>ASP.NET Survey</h1>";
ltlResult.Text += "<br/>Know fast?" + aspNetResults.KnowFast;
ltlResult.Text += "<br/>Know newest?"+ aspNetResults.KnowNewest;
break;
default:
break;
}
}
private Control _survey = null;
//通过DropDownList选择不同的用户控件,在PlaceHolder控件中呈现
protected void Page_Load(object sender, EventArgs e)
{
switch (ddlSelect.SelectedIndex)
{
//这里的"UserControls/ASPSurvey.ascx"路径是相对于呈现它的页面的
case 1: _survey = Page.LoadControl("UserControls/ASPSurvey.ascx");
break;
case 2: _survey = Page.LoadControl("UserControls/ASPNETSurvey.ascx");
break;
default:
break;
}
if (_survey!=null)
{
PlaceHolder1.Controls.Add(_survey);
}
}
//点击提交按钮之后,将用户控件中暴露的属性呈现在Literal控件中
protected void btnSubmit_Click1(object sender, EventArgs e)
{
switch (ddlSelect.SelectedIndex)
{
case 1:
//转换为相应的用户控件,以便提取它的属性
ASPSurvey aspResults = (ASPSurvey)_survey;
ltlResult.Text = "<h1>ASP Survey</h1>";
ltlResult.Text += "<br/>Know slow?" + aspResults.KnowSlow;
ltlResult.Text += "<br/>Know outdated?"+aspResults.KnowOutdated;
break;
case 2:
ASPNETSurvey aspNetResults = (ASPNETSurvey)_survey;
ltlResult.Text = "<h1>ASP.NET Survey</h1>";
ltlResult.Text += "<br/>Know fast?" + aspNetResults.KnowFast;
ltlResult.Text += "<br/>Know newest?"+ aspNetResults.KnowNewest;
break;
default:
break;
}
}
至于怎样暴露属性,这里我就不用多解释了。其实暴露属性比较容易理解,只需要写一个公开属性就可以了;倒是暴露事件就不是那么容易理解,倘若哪位高手有好的公开事件的例子,请公开分享,谢谢!