Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET Load WebUserControl Programmatically and Invoke Method using Reflection

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
14 Oct 2010CPOL1 min read 22.2K   3   4   3
Invoking method in a WebUserControl that is loaded programmatically
To answer the question as to how to invoke a method in a WebUserControl that is being loaded programmatically, I put together sample code to reveal the answer based on different access levels. I am sharing that code here.

Introduction

A few days ago, someone asked me how to invoke a method in a WebUserControl that is being loaded programmatically.

I took the opportunity to put together sample code to reveal the answer based on different access levels.
I hope all of you will find this information useful. The sample code is available to download from the link at the top of this page.

Putting Everything Together

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

Listing 1

C#
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 this code to retrieve the Control Type. Notice that the BaseType property is being used instead of 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

C#
MethodInfo method = cType.GetMethod("Method1");

        if (method != null)
        {
            method.Invoke(webControl, null);
        }

Invoke the public method with one argument.

Listing 5

C#
method = cType.GetMethod("MethodWithOneArg");
        if (method != null)
        {
            method.Invoke(webControl, new object[] { "hello" });
        }

Invoke the public method with multiple arguments.

Listing 6

C#
method = cType.GetMethod("MethodWithTwoArg");
        if (method != null)
        {
            method.Invoke(webControl, new object[] { "Number", 1000 });
        }

Invoke private method in the WebUserControl.

Listing 7

C#
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

C#
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

C#
method = cType.GetMethod("ProtectedMethod", BindingFlags.NonPublic | BindingFlags.Instance);

        if (method != null)
        {
            method.Invoke(webControl, null);
        }

Invoke internal method in the WebUserControl.

Listing 10

C#
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

C#
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

C#
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

C#
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

C#
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

C#
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

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

Resources

History

  • 15th October, 2010: Initial version

License

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


Written By
Software Developer (Senior)
United States United States
I have over 10 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

 
QuestionCall to a webUserControl method by reflection directly from target type Pin
iurdin2-Jul-15 21:50
iurdin2-Jul-15 21:50 
GeneralReason for my vote of 5 useful Pin
aptx159613-Jan-11 6:59
aptx159613-Jan-11 6:59 
GeneralReason for my vote of 5 Thanks for you tips Pin
ideamadasamy11-Jan-11 18:49
ideamadasamy11-Jan-11 18:49 

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

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