Steve C. Orr

Software Engineer, Web Developer, Database Designer
 
  

 

Q: How do I pass data to a user control?

A: User controls often contain many controls within them. Sometimes it’s handy to be able to set the properties of those sub controls from within the page’s code-behind. I’ve witnessed much confusion about how to do this. Here’s a best-practice solution in three easy steps:

Step 1: In the user control’s code-behind file, create a public method or property that the page will call. In the following example, the user control contains a Label control. This example sets the encapsulated label’s Text property with the supplied parameter value:

Public Sub SetLabelText(ByVal val As String)

    Label1.Text = val

End Sub

 

Step 2: Within the code-behind class of the page, declare a strongly-typed reference to the user control:

Protected WithEvents MyControl1 As MyUserControl

This control is automatically instantiated by ASP.NET, so you don’t need the New keyword.

 

Step 3: Now you can call the user control’s custom method from within the page:

MyControl1.SetLabelText("Value set from page code behind")

Passing values from the page to one of its user controls is nice, but what about the reverse scenario?


 

(advertisement)