如何使用LoadControl方法动态加载UserControl(Type,object [])

时间:2011-09-27 06:22:08

标签: c# asp.net user-controls

我对用户控件有点新意。我的用户控件类是ucDefault。我没有明确指定任何构造函数。我必须使用默认构造函数加载我的用户控件。我该怎么做 ?

1 个答案:

答案 0 :(得分:2)

尝试,

Control control=LoadControl("~/UserControlFile.ascx");

我发布的帖子答案:

  1. How to load a web usercontrol from a physical path rather than a virtual path
  2. Loading web user controls from blob storage in asp.net
  3. 编辑:

    这是位于App_code

    的TestControl.cs
    public class TestControl : UserControl
    {
        public TestControl() { }
        public TestControl(string message)
        {
            SayHello = message;
        }
        public string SayHello { get; set; }
    
        public override void RenderControl(HtmlTextWriter writer)
        {
            base.RenderControl(writer);
            writer.Write(SayHello);
        }
    }
    

    和加载/创建控制对象的代码:

    TestControl tc = (TestControl)LoadControl(typeof(TestControl), new object[] { "Hello Buddy" });