如何动态加载web用户控件
本文关键字:加载 web 用户 控件 动态 何动态 | 更新日期: 2023-09-27 18:23:49
这是一个非常重要的问题。这让我在4个小时内疯了:(我可以加载UCAddX.ascx,但如果我点击"在X中搜索"按钮,就不会加载UCSearchX用户控件。有3个按钮也有3个网络用户控件。我想在点击事件后加载这3个网络用户控件。但下面的方法不起作用。如何动态加载网络用户控件?点击(像选项卡控件一样)
public partial class MyPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
{
AddUserControl();
}
else
{
AddUserControl();
}
}
protected void btnAddX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnSearchX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "SearchX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnUpdateX_Click(object sender, DirectEventArgs e)
{
}
void AddUserControl()
{
// plhContent1.Controls.Clear();
if (ViewState["controlType"] != null)
{
if (ViewState["controlType"].ToString() == "AddX")
{
UCAddX uc = (UCAddX)Page.LoadControl("~/Pages/EN/MyUserControls/UCAddX.ascx");
uc.ID = "ucAddX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
else if (ViewState["controlType"].ToString() == "SearchX")
{
UCSearchX uc = (UCSearchX)Page.LoadControl("~/Pages/EN/MyUserControls/UCSearchX.ascx");
uc.ID = "ucSearchX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
}
}
}
使用下面的代码动态加载用户控件
var control = LoadControl(filePath) as ControlType;
然后您可以订阅事件并添加到控件占位符。
希望这能帮助
试试这样的东西,
//to load the control
protected void Page_Init(object sender, EventArgs e)
{
ViewState["controlType"] = "AddSector";
//you don't need to check the if condiontion, cause you load every time the controls
AddUserControl();
}
当你需要在回发后从控件中获取值时,你应该在上获取它
protected void Page_PreRender(object sender, EventsArgs args) {
//your placeholder that contains data
}
动态加载的用户控件需要在每个Page_Load上加载,以便保持其视图状态。所以你需要这样的东西:
public string CurrentControlToLoad
{
get
{
if(ViewState["controlType"] == null)
return "";
return (string)ViewState["controlType"];
}
set
{
ViewState["controlType"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(CurrentControlToLoad != "")
LoadControl(CurrentControlToLoad);
}
protected void btnAddSector_Click(object sender, DirectEventArgs e)
{
CurrentControlToLoad = "AddSector";
LoadControl(CurrentControlToLoad);
}