public partial class UserControl_Simulation_ProjectNeedsManagement : System.Web.UI.UserControl
{
private ArrayList arrProjectID
{
get
{
if (ViewState["ControlCount"] == null)
ViewState[
"ControlCount"] = new ArrayList();
return (ArrayList)ViewState["ControlCount"];
}
set
{
ViewState[
"ControlCount"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ProjectBind();
}
foreach(int id in arrProjectID)
{
LoadUserControl(id);
}
}
protected void btnAddProject_Click(object sender, EventArgs e)
{
int id = Convert.ToInt16(ddlProjectSimulation.SelectedValue);
if (!arrProjectID.Contains(id))
{
arrProjectID.Add(id);
LoadUserControl(id);
}
else
{

}
}
private void ProjectBind()
{
List
<ProjectInfo> projInfoLi = ProjectList.GetAllSimulationProject();
ddlProjectSimulation.DataSource
= projInfoLi;
ddlProjectSimulation.DataTextField
= "ProjectName";
ddlProjectSimulation.DataValueField
= "ID";
ddlProjectSimulation.DataBind();
}

private void LoadUserControl(int id)
{
UserControl_Simulation_JobFamilyNeedsManagement ucJobFamilyNeedsManagement
= (UserControl_Simulation_JobFamilyNeedsManagement)LoadControl("JobFamilyNeedsManagement.ascx");
ucJobFamilyNeedsManagement.ID
= "ucjf" + id;
ucJobFamilyNeedsManagement.ProjectInfo
= ProjectList.GetSimulationProject(id);
pan.Controls.Add(ucJobFamilyNeedsManagement);
}
}

      动态添加控件,很多时候需要动态添加用户控件包括usercontrol或asp.net控件。但页面提交后我们要保持控件内容不变,可由于页面的执行顺序导致控件重新加载,数据丢失。

      由于页面viewstate tree保存是通过ID对应,所以我们在添加控件时可以给添加的控件加一个固定ID,然后存在viewstate中,每次页面加载时添加ID为这些的用户控件。如本例的代码中就是以projectid作为加载的usercontrol的固定id。

      加载usercontrol用loadcontrol(address)方法。

posted on 2011-03-06 12:04  长风一剑  阅读(332)  评论(0编辑  收藏  举报