tags:

views:

29

answers:

1

I have a User Control with a label on it. I have a Master Page that I have dropped the User Control on. I have other .aspx pages that use the master page that has the user control on it.

What is the best way to change the text of that label on the user control from the .aspx page?

+3  A: 

You have a couple of options but the best way would be to create a method on the user control that wraps the text property of your label and allows users to pass in a value that you in turn assign to the label's Text property.

Then create another method on your Master Page that accepts a string parameter and passes that value through to the method on your user control. Then you can call this method on your Master Page from your web form.

So on your user control add a method like this:

Public Sub SetDisplayText(ByVal displayText As String)
    SomeLabel.Text = displayText
End Sub

then add a method to your Master Page like this:

Public Sub SetDisplayText(ByVal displayText As String)
    SomeUserControl.SetDisplayText(displayText)
End Sub

Now your web form can call the SetDisplayText method on the Master Page to set the text on the user control's label:

Dim masterPage As SomeMasterPage = TryCast(Me.Master, SomeMasterPage)

If masterPage IsNot Nothing Then
    masterPage.SetDisplayText("foo")
End If

This may feel like overkill but this kind of abstraction is necessary to reduce coupling between your components. This approach also gives you a lot of flexibility moving forward as changes can be made without affecting other components. For instance, if you rename your label control you will not need to go change the web form that sets its text value as the web form won't know (or care) what the label is called, only how to set its display value.

Andrew Hare