代码之家  ›  专栏  ›  技术社区  ›  spacemonkeys

自定义控件,动态创建

  •  0
  • spacemonkeys  · 技术社区  · 15 年前

    我已经在ASP.NET中创建了一个自定义控件,如果我将它拖到另一个网页上,它可以正常工作,正如预期的那样,但是我想像在中一样动态地使用它

       Dim lCustomControl as new cldButton
    

    但是我不知道怎么做,编译器不会将cldbutton重新编码为控件,我将把它添加到代码的后面一页。我已经将以下内容添加到web.config中。

    <controls>
            <add tagPrefix="cldButton" tagName="cldButton" src ="~/UserControls/customControlButton.ascx"/>
    

    但这似乎和我打字的方式有很大的不同

    谢谢

    2 回复  |  直到 15 年前
        1
  •  2
  •   Jeff Siver    15 年前

    您需要使用page.loadcontrol方法,而不是执行新操作来创建自定义控件。这是C语法(对不起,我不是vb.net的人);应该很容易转换:

    Control customControl = Page.LoadControl("mycustomercontrol.ascx");
    customControl.ID = "someID";
    ICustomControl customControlType = (ICustomControl) customControl;
    

    我使用网站,所以我必须为自定义控件创建一个接口,并以这种方式管理它。如果使用Web应用程序,则可以将CustomControl权利强制转换为控件的类型。

    并且,在完成所有设置之后,您需要将控件添加到其容器中(我通常使用占位符控件)。

        2
  •  1
  •   womp    15 年前

    也许我误解了这个问题,但是如果您只是在谈论使用代码(而不是标记)创建控件,那么您不需要向web.config文件中添加任何内容。

    只需实例化控件的一个新实例,并在页面初始化期间将其添加到页面的控件集合中。

    Dim myControl As new cldButton
    
    Page.Controls.Add(myControl)