Professional Web Applications Themes

Dynamic Control Creation with Reflection? - ASP.NET Building Controls

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....

  1. #1

    Default Dynamic Control Creation with Reflection?


    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.

    localhost Guest

  2. #2

    Default RE: Dynamic Control Creation with Reflection?

    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
    [url]http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemReflectionAsse[/url]
    mblyClassGetAssemblyTopic.asp?frame=true

    #Assembly.CreateInstance Method
    [url]http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemReflectionAsse[/url]
    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

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

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





    Steven Cheng[MSFT] Guest

  3. #3

    Default Re: Dynamic Control Creation with Reflection?


    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.



    On Fri, 25 Jun 2004 02:10:49 GMT, [email]v-schangonline.microsoft.com[/email]
    (Steven Cheng[MSFT]) wrote:
    >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?
    >
    localhost Guest

  4. #4

    Default Re: Dynamic Control Creation with Reflection?

    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.WebCont rols.TextBox","txtDynamic"
    ,"Dynamic TextBox");

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

    Button btn =
    (Button)GetControlInstance("System.Web.UI.WebContr ols.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.WebContr ols.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

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

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

    Steven Cheng[MSFT] Guest

  5. #5

    Default Re: Dynamic Control Creation with Reflection?


    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

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

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

    Steven Cheng[MSFT] Guest

Similar Threads

  1. Replies: 2
    Last Post: February 13th, 10:36 AM
  2. Replies: 0
    Last Post: February 13th, 09:58 AM
  3. Dynamic control creation in datagrid based on data in that column
    By mitramay@gmail.com in forum ASP.NET Building Controls
    Replies: 1
    Last Post: September 24th, 05:51 AM
  4. Replies: 0
    Last Post: April 6th, 11:13 PM
  5. Dynamic Control Creation w/Events?
    By Jeff Voigt in forum ASP.NET General
    Replies: 1
    Last Post: July 8th, 07:08 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139