c# - 在按钮单击、回发问题上动态加载用户控件

标签 c# asp.net

我试图在单击按钮时加载用户控件,但问题是,它在用户控件内的回发时消失了。

这是我加载控件的方式:

private bool IsUserControl
{
    get
    {
        if (ViewState["IsUserControl"] != null)
        {
            return (bool)ViewState["IsUserControl"];
        }
        else
        {
            return false;
        }
    }
    set
    {
        ViewState["IsUserControl"] = value;
    }
}


#region Usercontrols
private void CreateUserControlAllNews()
{
    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
    plh1.Controls.Add(featuredProduct);
}

#endregion
protected void allNewsbtn_Click(object sender, EventArgs e)
{

    this.IsUserControl = true;
    if(IsUserControl)
    CreateUserControlAllNews();
}

最佳答案

您需要在回发页面时重新加载控件。例如,

protected void Page_Load(object sender, EventArgs e)
{
    if (IsUserControl)
    {
        CreateUserControlAllNews();        
    }
}

private void CreateUserControlAllNews()
{
    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
    featuredProduct.ID = "1234";
    plh1.Controls.Add(featuredProduct);
}

关于c# - 在按钮单击、回发问题上动态加载用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14461452/

相关文章:

c# - 如何使用任务并行库执行多个任务并在第一个任务实际返回数据后返回

c# - Mvc 不存在于命名空间 system.web 中

c# - 为什么 `Microsoft.JScript` 在代码隐藏中工作,但在 `<% %>` 中不起作用?

asp.net - VB.NET Directory.GetFiles 按日期排序

c# - 在 Google map 标记中添加文本

c# - Unity中启用、isActiveAndEnabled和activeInHierarchy的区别

c# - 在 C# 中为 INSERT 语句定义 SQL 参数

c# - 通过在 c# 中使用 console.writeline 获取 byte [][] 的输出,servicestack

asp.net - jQuery $(document).ready() 未触发

c# - 通过 C# Web Service 获取更新的 APK 版本并安装