这是非常重要的问题。这让我疯狂4小时:(我可以加载UCAddX.ascx,但如果我点击“在X中搜索”按钮不加载UCSearchX用户控件。有3个按钮也有3个Web用户控件。我想加载这3个web clickEvents之后的用户控件。但是下面的方法不能正常工作。如何动态加载Web用户控件?单击按点击(如Tab控件)
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);
}
}
}
}
答案 0 :(得分:1)
使用以下代码动态加载usercontrol
var control = LoadControl(filePath) as ControlType;
然后您可以订阅事件并添加到控件占位符。
希望这有帮助
答案 1 :(得分:0)
尝试这样的事情,
//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
}
答案 2 :(得分:0)
动态加载时的用户控件需要在每个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);
}