This is a fantastic problem that I faced. I was having a user control in my asp.net application as MSDD.ascx. I wanted to dynamically display this user control from the code written in the Dynamic.cs file in app_code folder of my applicaiton. But at this movement, I was unable to access the MSDD class written in codebehind file from my class in app_code. How can we proceed now???
Solution:
The best solution is to write an Interface. Place this interface in the app_code folder of you application. The aspx codebehind class should implment this particular interface. Now via interface you can access the codebehind class from you class in app_code folder. See the scenario below:
I have following files:
ASPX: A user control/class named MSDD.
app_code: A call named Dynamic, in which I want to access the above user control class MSDD.
Now write an interface IMSDD and make the codebehind class MSDD to implement this IMSDD interface. So you MSDD class will look like:
public
class MSDD : IMSDD{
// Code here...}
And your Dynamic class which uses the Interface will look like:
public
class Dynamic{
IMSDDctrl = (IMSDD) Page.LoadControl("../MSDD.ascx");
// Now using this interface you can invoke any method/property of the MSDD class this is exposed via the interface.ctrl.Invoke();
}
Hope this helps you...
1 comments:
Hi,
it helped.
For your particular problem you could try creating entirely dynamic controls: such as :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace GUI.Controls
{
[DefaultProperty ( "Text" )]
[ToolboxData ( "<{0}:ControlName runat=server>" )]
[ParseChildren ( false )]
public class ControlName : WebControl
{
#region Properties
#region Caption
protected string _Caption = "";
[Bindable ( true )]
[Category ( "Appearance" )]
[DefaultValue ( "" )]
[Localizable ( true )]
public string Caption // Public properties
{
get { return _Caption; }
set { _Caption = value; }
}
#endregion Caption
#region Text
protected string _Text = "";
[Bindable ( true )]
[Category ( "Appearance" )]
[DefaultValue ( "" )]
[Localizable ( true )]
public string Text // Public properties
{
get { return _Text; }
set { _Text = value; }
}
#endregion Text
#endregion Properties
#region Constructors
public ControlName ()
{
//Statement to run while initialize of control
}
#endregion Constructors
#region Overrides
public override void RenderControl ( HtmlTextWriter writer )
{
RenderContents ( writer );
}
protected override void RenderContents ( HtmlTextWriter output )
{
//Codes for rendering html to be written here
output.WriteBeginTag ( "div" );
output.WriteAttribute ( "class", _Caption );
RenderChildren ( output ); // Render Child Control is Exists
output.WriteEndTag ( "div" );
}
#endregion Overrides
} //eof class
} //eof namespace
Post a Comment