XstreamINsanity
XstreamINsanity

Reputation: 4296

VB.Net ASP: Access controls in a user control

I have a couple user controls that are loaded by a Select Case statement. However, in the behind code file for the main page that loads these controls, none of the asp controls show up in intellisense. I had a feeling it's because the controls are loaded conditionally. My question is what is the best way to solve this?

1) Load the controls and do a Select Case in the behind code to make them hidden or not.

2) Is there a way to say (psuedocode): LoadUserControl("UserControl1").Controls("tbTest").Text = ""

3) How can I pass a dataset to the User Control file?

4) Any other ideas?

Thanks.

Update

This allows me to load the control and access values in the sub-controls. However, the update doesn't seem to work. Any ideas?

Private Sub SetFrequencyValues(ByVal frequency As Integer)
    Select Case frequency
        Case 2
            Dim userControl As Minutes = CType(LoadControl("Frequency/Minutes.ascx"), Minutes)
            Dim tb As TextBox = userControl.FindControl("tbMinutes")
            tb.Text = "10"
            tb.Visible = False
        Case(4)
        Case 5
        Case 6
    End Select
End Sub

Upvotes: 1

Views: 4471

Answers (1)

Luke
Luke

Reputation: 8407

If you know what Controls will be displayed you can ctype them to your control

dim uc as MyUserControl = cType(LoadUserControl("UserControl1"), MyUserControl)

and your MyUserControl could have some properties, that you might want to set

MyUserControl.Data = mySelectedData

If you dont same controls, you might consider using interfaces

Public Interface IDataForUserControl
    Public Property Data as Object
End Interface

Then you can implement this Interface, and if you load it, you could try cast it into the interface.

If you dont have these two possibilities, you could work with ITemplates and NamingContainers.

Dim control as new MyNamingContainerThatImplementsIDataItem
LoadTemplate("UserControl1").instantiateIn(control)

Than you could in your UserControl1 access the Data using DataBinder.

Answer for your Update

There might be some overriding somewhere. When are you calling your update function? Maybe the mintues.ascx is setting the same data on "load" event or something.

You could either create a method in the "userControl" that you would access in the SetFrequencyValues method, and then it may not be touched anymore. Or you handle some event of your usercontrol

dim userCOntrol as Minutes = Loadcontrol("Minutes.ascx")
AddHandler userControl.load, sub(sender as Minutes, e as eventargs)
                                  sender.mytextbox.text = "10"
                             end sub

Or on prerender, what ever you want.

Upvotes: 1

Related Questions