Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / Building Controls / June 2004

Tip: Looking for answers? Try searching our database.

Dynamic Control Creation with Reflection?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
localhost - 24 Jun 2004 22:46 GMT
I have a DataTable with String-typed columns that looks like this:
    [Col1]        [Col2]        [Col3]
    "TextBox"     "txtTest"    "Enter Here"
   

Strictly programmtically in my code-behind, I want to create a TextBox
control on my page called txtTest with text inside already "Enter
Here".  How would I do that using Reflection (or is there a better
way)?

Thanks.
Steven Cheng[MSFT] - 25 Jun 2004 03:10 GMT
Hi Localhost,

From your description, you have  a DataTable which contains three string
fields(which represents asp.net server control's Type, Id and Text ) and in
your asp.net web page, you'll programmatically create controls according to
the datas get from the DataTable, yes?

I think the "[Col2]" and "[Col3]", just (Id and Text property) is not the
main problem. Our problem here is focus on how to dynamically create a
control instance of a type(getting through a string value) ,yes?  
The Reflection you mentioned is possbile to perform this, in .net , we can
load an assembly's instance via a specified Type and create a certain Type(
in this assembly)'s instance via the interfaces under the
System.Reflecdtion namespace, here are some of the interfaces' referencein
MSDN:

#Assembly.GetAssembly Method
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemReflectionAsse
mblyClassGetAssemblyTopic.asp?frame=true

#Assembly.CreateInstance Method
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemReflectionAsse
mblyClassCreateInstanceTopic.asp?frame=true

However, use Reflection will cause strict performance issue and is not
recommended to use in serverside application such as asp.net web
application. Especially for your scenario, you create a large number of
controls this way may make the application very restricted.

Instead of using Reflecdtion, I think you can consider use a switch block
to determine which type of control to instance at runtime, such as

public Control GetControlInstance(string ctrl)
{
swtich(ctrl)
{
case "TextBox":
return new TextBox();
case "Label":
..
case "CheckBox":

..........

}
}

How do you think of this? Also, if you have any futher ideas, please also
feel free to post here.

Regards,

Steven Cheng
Microsoft Online Support

Signature

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Signature

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx

localhost - 25 Jun 2004 15:08 GMT
I am aware of how to do that with a switch statement, and also about
Reflection speed penalties.

However, I need to use Reflection for other reasons that will just
muddle/confuse this post.  

Can you show a simple code example of how to do this?  Just say I have
three strings:
  string1 = "TextBox";
  string2 =  "myTextBox";
  string3 = "Enter Here";
And now I want to use Reflection to create a new TextBox called
myTextBox with a default text value of "Enter Here".

Thanks.

>Hi Localhost,
>
>From your description, you have  a DataTable which contains three string
>fields(which represents asp.net server control's Type, Id and Text ) and in
>your asp.net web page, you'll programmatically create controls according to
>the datas get from the DataTable, yes?
Steven Cheng[MSFT] - 28 Jun 2004 08:31 GMT
Hi Localhost,

Thanks for your followup. As for the code snip on use Reflection api to
dynamically create controls , here is a simple Demo page I've made, its in
C# code , hope helps.

============aspx page==========================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <title>dynamiccontrols</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="FlowLayout">
        <form id="Form1" method="post" runat="server">
            <asp:PlaceHolder id="phMain" runat="server"></asp:PlaceHolder></form>
    </body>
</HTML>

==============code behind code====================

namespace FormAuthApp.reflection
{
    /// <summary>
    /// Summary description for dynamiccontrols.
    /// </summary>
    public class dynamiccontrols : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.PlaceHolder phMain;
   
        private void Page_Load(object sender, System.EventArgs e)
        {
            TextBox txt =
(TextBox)GetControlInstance("System.Web.UI.WebControls.TextBox","txtDynamic"
,"Dynamic TextBox");
           
            if(txt != null)
            {
                phMain.Controls.Add(txt);
            }

            Button btn =
(Button)GetControlInstance("System.Web.UI.WebControls.Button","btnDynamic","
Dynamic Button");

            if(btn != null)
            {
                phMain.Controls.Add(btn);
            }

        }

        public object GetControlInstance(string type, string id, string text)
        {
            object ctrl = null;
            try
            {

                Assembly asm =
Assembly.GetAssembly(typeof(System.Web.UI.WebControls.WebControl));
                Type tp = asm.GetType(type,true,true);
                ctrl = asm.CreateInstance(type,true);
           
                tp.InvokeMember("ID",
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField |
BindingFlags.SetProperty | BindingFlags.IgnoreCase , null, ctrl, new
Object[]{id});
                tp.InvokeMember("Text",
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField |
BindingFlags.SetProperty | BindingFlags.IgnoreCase , null, ctrl, new
Object[]{text});
       
            }
            catch(Exception ex)
            {
                Response.Write("<br>" + ex.Message);
            }
            return ctrl;
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
       
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion
    }
}
====================================

Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Signature

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Signature

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx

Steven Cheng[MSFT] - 30 Jun 2004 10:46 GMT
Hi Localhost,

Have you had a chance to check out the suggestions in my last reply or have
you got any further ideas on this issue? If you have anything unclear or if
there're anything else we can help, please feel free to post here. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Signature

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


Signature

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.