简体   繁体   中英

Asp.Net: Dynamically switching UserControl - How?

In Asp.Net is it possible to dynamically switch which user control gets loaded with the .aspx page.

Depending on the type of news story I would like to switch which control gets loaded.

Thanks melt

Put a place holder in your page and in your code-behind file load the control on a if/then/else or switch/case logic method. That's the easiest way I see the implementation.

Use LoadControl(), which is an instance method on the Page class. Then simply add it to a container's Controls collection.

             if (mytype=="news")  
             {  
                 //load the required usercontol  
                 ph.Controls.Add(LoadControl("~/usercontrols/news.ascx"));
             }  
             else  
             {  
                 ph.Controls.Add(LoadControl("~/usercontrols/somethingelse.ascx"));
             }

With "ph" being an asp:PlaceHolder control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM