Subscribe

RSS Feed (xml)

Programmatically Accessing Properties of a Late-Bound User Control

In this example, you have a simple greeting User Control that exposes two properties
and a method.You set one property using late binding and the other property using
reflection.You then invoke the method using reflection.The User Control uses these
properties to display a Label that holds a combination of these values.The code for the
User Control is available from this book’s support Web site.When you declare the User
Control on the page, you also set its username property declaratively—this property will
be overridden at runtime by the code in Page_Load().

The ASPX page:
<form id=”Test” method=”post” runat=”server”>
<uc1:Recipe0208vb id=”Recipe0208vb1” runat=”server”
username=”Steve”></uc1:Recipe0208vb>
</form>

In <script runat=”server” /> block or codebehind:
Protected Recipe0208vb1 As Object
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
‘Late binding call will override declarative setting
‘Only works in VB, not C#
Recipe0208vb1.UserName = “Rob”
‘Reflection
Dim myControl As Control = Page.FindControl(“Recipe0208vb1”)
Dim myControlType As Type = myControl.GetType()
Dim GreetingProperty As PropertyInfo =
myControlType.GetProperty(“Greeting”)
GreetingProperty.SetValue(myControl, “Guten Tag, “, Nothing)
Dim MessageMethod As MethodInfo = myControlType.GetMethod(“AddMessage”)
Dim Params() As Object = New Object()
{“This message was added using reflection!”}
MessageMethod.Invoke(myControl, Params)
End Sub

There are two ways to do this.The first one only works in Visual Basic and uses late binding.
It works only when Option Strict is turned off, and allows variables declared as
Object to use methods and properties that are not known at compile time. In general, it
is not a good idea to use late binding if you can avoid it. However, one of the advantages
of VB over C# is that it supports late binding, which provides a much simpler mechanism
than reflection for tasks like the one described in this section.
The second technique uses a process called reflection, which uses classes found in the
System.Reflection namespace.The net effect is the same as with late binding, but the
calls are much more explicit, and there is a lot more code. Because reflection is built into
the .NET Framework, it will work with any .NET language.

No comments:

Archives

Variety in the Web World