【问题标题】:How to embed user control (ascx) from code behind C#?如何从 C# 后面的代码嵌入用户控件(ascx)?
【发布时间】:2014-07-14 23:00:46
【问题描述】:

将用户控件嵌入到 html 页面很容易,但是从 c# 后面的代码中动态嵌入用户控件呢?任何帮助/建议将不胜感激。

【问题讨论】:

    标签: c# html visual-studio user-controls ascx


    【解决方案1】:

    使用LoadControl 动态加载和创建控件。然后你可以将它添加到页面的控件集合中。

    UcType myControl = (UcType) LoadControl("UcType.ascx");
    this.SomeContainerContainerControl.Controls.Add(myControl);
    

    其中UcType 是UserControl 的类型,SomeContainerContainerControl 是您要添加此uc 的控件,例如Panel。 如果您想将其添加到页面顶部,只需使用this.Controls.Add(myControl)。

    您应该将其添加到Page_Init 或Page_Load(最迟)。您必须在每次回发时重新创建它,就像使用与以前相同的 ID(如果有)的每个其他动态控件一样。

    【讨论】:

    • 它应该是UcType myControl = (UcType) LoadControl("UcType.ascx");(没有.cs),否则它会抛出一个InvalidCastException。
    • 感谢您的关注。我不确定,因为 MSDN 还显示了一个带有 .cs 的示例。
    【解决方案2】:

    您可以使用 LoadControl() 方法并将其加载到内容控件中

    示例:

    protected void Page_Load(object sender, EventArgs e)
    {
        controls_example exmp = LoadControl("controls/example.ascx") as controls_example;
        myContentPanel.Controls.Add(exmp);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      相关资源
      最近更新 更多