What is the best way to change the label text in a user control?

I have a User Control with a label on it. I have a main page to which I disabled the User Control. I have other .aspx pages that use a master page that has a user control on it.

What is the best way to change the text of this label in a user control from an .aspx page?

+4
source share
1 answer

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

Then create another method on the main page that takes a string parameter and passes that value to the method in your user control. You can then call this method on your main page from your web form.

So, in your user element add the following method:

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

then add the method to your main page as follows:

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

Now your web form can call the SetDisplayText method on the main page to set the text on the user control shortcut:

 Dim masterPage As SomeMasterPage = TryCast(Me.Master, SomeMasterPage) If masterPage IsNot Nothing Then masterPage.SetDisplayText("foo") End If 

This may seem redundant, but this abstraction is necessary to reduce the connection between your components. This approach also gives you great flexibility in moving forward, as changes can be made without affecting other components. For example, if you rename your label control, you will not need to change the web form that sets its text value, because the web form will not know (or do not care) about what is called a label, only how to set its display value.

+5
source

Source: https://habr.com/ru/post/1299853/


All Articles