Monday 21 March 2011

Adding instance of WebUserControl to ASP.Net website project

It can easily be done using namespaces. Here's an example:




WebControl1.ascx:



Notice that Inherits references the namespace (MyUserControls), and not just the class name (WebControl1)



WebControl1.ascx.cs:



namespace MyUserControls { public partial class WebControl1 : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } } Notice that the class have been included in the namespace MyUserControls



Default.aspx.cs:



using MyUserControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var control = (WebControl1) Page.LoadControl("~/WebControl1.ascx"); } } This approach potentially allow you to redistribute your user controls (or keep them in a separate project) without the hassle of referencing them in your .aspx files.

No comments: