Click here to Skip to main content
Click here to Skip to main content

Tagged as

ASP.NET Load WebUserControl programmatically and invoke method using Reflection

, 14 Oct 2010 CPOL
Rate this:
Please Sign up or sign in to vote.

Introduction

 


A few days ago, someone has asked me how to invoke a method in a WebUserControl that is being loaded programmatically.
I took the opportunity to put together a sample code to reveal the answer based on different access level.
I hope you all will find this information useful. Sample code is available to download.

 

Putting everything together

Shown in Listing 1 is the code behind of the WebUserControl.



Listing 1

 
public string Text
    {
        get { return TextBox1.Text; }
        set { TextBox1.Text = value; }
    }
 
    public static string staticVar = "Static Value";
    public const string constVar = "Constant Value";
 
    public void Method1()
    {
        Label1.Text = "Invoked public method with no argument";
    }
 
    public void MethodWithOneArg(string arg1)
    {
        Label2.Text = "Invoked public method with one argument, value: " + arg1;
    }
 
    public void MethodWithTwoArg(string arg1, int arg2)
    {
        Label3.Text = string.Format("Invoked public method with two argument, value: {0} and {1}", arg1, arg2.ToString());
    }
 
    private void PrivateMethod()
    {
        Label4.Text = "Invoked private method";
    }
 
    private void PrivateMethodWithArgs(string arg1, int arg2, string arg3)
    {
        Label5.Text = string.Format("Invoked private method with three argument, value: {0} , {1} and {2}", arg1, arg2.ToString(), arg3);
 
    }
 
    protected void ProtectedMethod()
    {
        Label6.Text = "Invoked protected method";
    }
 
    internal void InternalMethod()
    {
        Label7.Text = "Invoked internal method";
    }
 
    public string MethodWithReturnValue()
    {
        return "hello from UC";
    }
 
    public string MethodWithReturnValue(string arg1)
    {
        return "hello " + arg1;
    }
 
 


Here is the code to load the WebUserControl



Listing 2

UserControl webControl = (UserControl)Page.LoadControl("~/uc/WebUserControl.ascx");
Use the following code to retrieve the Control Type. Notice that the BaseType property is being used instead GetType()
method itself in order to access private, static and constant fields using reflection.



Listing 3
Type cType = webControl.GetType().BaseType;
Invoke the public method.



Listing 4
MethodInfo method = cType.GetMethod("Method1");
 
        if (method != null)
        {
            method.Invoke(webControl, null);
        }
Invoke the public method with one argument.



Listing 5
method = cType.GetMethod("MethodWithOneArg");
        if (method != null)
        {
            method.Invoke(webControl, new object[] { "hello" });
        }
 
Invoke the public method with multiple arguments.



Listing 6
method = cType.GetMethod("MethodWithTwoArg");
        if (method != null)
        {
            method.Invoke(webControl, new object[] { "Number", 1000 });
        }
 
Invoke private method in the WebUserControl.



Listing 7
method = cType.GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
 
        if (method != null)
        {
            method.Invoke(webControl, null);
        }
 
Invoke private method with multiple arguments in the WebUserControl



Listing 8
method = cType.GetMethod("PrivateMethodWithArgs", BindingFlags.NonPublic | BindingFlags.Instance);
 
        if (method != null)
        {
            method.Invoke(webControl, new object[] { "arg1", 5555, "arg 2" });
        }
Invoke protected method in the WebUserControl



Listing 9
method = cType.GetMethod("ProtectedMethod", BindingFlags.NonPublic | BindingFlags.Instance);
 
        if (method != null)
        {
            method.Invoke(webControl, null);
        }
Invoke internal method in the WebUserControl



Listing 10
method = cType.GetMethod("InternalMethod", BindingFlags.NonPublic | BindingFlags.Instance);
 
        if (method != null)
        {
            method.Invoke(webControl, null);
        }
Invoke overload method and capture the return value.



Listing 11
method = cType.GetMethod("MethodWithReturnValue", Type.EmptyTypes);
 
        if (method != null)
        {
            rValue = method.Invoke(webControl, null) as string;
            literal.Text += "Invoked overload method: " + rValue + "<br />";
        }
Invoke overload method with argument and capture the return value.



Listing 12
method = cType.GetMethod("MethodWithReturnValue",
            BindingFlags.Public | BindingFlags.Instance, null,
            new Type[] { typeof(string) }, null);
 
        if (method != null)
        {
            rValue = method.Invoke(webControl, new object[] { "there!" }) as string;
            literal.Text += "Invoked overload method with arguments: " + rValue + "<br />";
        }
Access the static field in the WebUserControl, get and set its value.



Listing 13
FieldInfo field = cType.GetField("staticVar");
 
        if (field != null)
        {
            rValue2 = field.GetValue(null) as string;
            literal.Text += "Static variable - before modify: " + rValue + "<br />";
            field.SetValue(null, "New static value");
            rValue2 = field.GetValue(null) as string;
            literal.Text += "Static variable - after modified: " + rValue2 + "<br />";
        }
Access the constant field in the WebUserControl.



Listing 14
field = cType.GetField("constVar");
        if (field != null)
        {
            rValue = field.GetValue(null) as string;
            literal.Text += "Constant variable: " + rValue + "<br />";
        }
Get and set the property in the WebUserControl through reflection.



Listing 15
PropertyInfo property = cType.GetProperty("Text");
 
        if (property != null)
        {
            //set
            property.SetValue(webControl, "Textbox value", null);
            //get
            rValue = property.GetValue(webControl, null) as string;
 
            literal.Text += "Set Textbox value to: " + rValue + "<br />";
        }
Get controls by ID and retrieve its value.



Listing 16
field = cType.GetField("TextBox1", BindingFlags.NonPublic | BindingFlags.Instance |
            BindingFlags.Public | BindingFlags.IgnoreCase);
 
        if (field != null)
        {
            rValue = ((TextBox)field.GetValue(webControl)).Text;
            literal.Text += "Find Control by ID: " + rValue + "<br />";
        }


Conclusion

If you find any bugs or disagree with the contents, please drop me a line
and I'll work with you to correct it.


 

Download

Download source
 

Resources

Get controls by name using reflection

Type.BaseType Property

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bryian Tan
Software Developer
United States United States
I have over three years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

 
GeneralReason for my vote of 5 useful Pinmemberaptx159613-Jan-11 7:59 
GeneralReason for my vote of 5 Thanks for you tips Pinmemberideamadasamy11-Jan-11 19:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 15 Oct 2010
Article Copyright 2010 by Bryian Tan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid