iterating through control array

inzo21

Regular
Joined
Nov 5, 2003
Messages
74
Hello all,

I have the following situation. I have a user control embedded in a web form that has a panel on it. Within the panel, there are other multiple user controls with their initial visibility set to false. When the user clicks on a link in the web form, I want it to set the visibility to true for a prticular user control in the panel. This works fine.

However, what I wanted to do is loop through all controls in the panel when the user clicks the linkbutton and set their visibility to off. I then locate the user control in question and set its visbility to on. This is where I'm having an issue. Here is the code I am using in the linkbutton, which is on the user control on the web form.

Dim myuc As UserControl = New UserControl
For Each myuc In Me.Controls
myuc.Visible = False
Next myuc
myuc = Me.FindControl("ucsub_x22release")
myuc.Visible = True

The error I get is this:

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:


Line 57: Private Sub lnk_contactnds_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnk_contactnds.Click
Line 58: Dim myuc As UserControl = New UserControl
Line 59: For Each myuc In Me.Controls
Line 60: myuc.Visible = False
Line 61: Next myuc


Source File: C:\Inetpub\wwwroot\xweb\corpinfo.ascx.vb Line: 59

Can anyone point me in the right direction on how to accomplish this?

Thanx in advance,

inzo
 
Try something like
Visual Basic:
 Dim myuc As UserControl    'you may be better using the correct control type here.
dim c as control
For Each c In Me.Controls
if typeof c is UserControl then
myuc.Visible = False
end if
Next 
myuc = Me.FindControl("ucsub_x22release")
myuc.Visible = True

also could you not just put the controls within a panel and change the panel's visibility rather than each control individually.
 
this reminded of something i was doing with validartion of control in a user control. what i was doing was iterating through the control collection to change the backcolor property of those control which are invalid. Well I have about 10 usercontrols each with this same sub in it to do this function. I was wondering if it was possible to move the sub to a single location and pass it the control collection. Any clue as to if this might work by moving it to a single location or should I just keep it in each usercontrol?
 
PlausiblyDamp said:
...also could you not just put the controls within a panel and change the panel's visibility rather than each control individually.

That is how I usually do it. The problem you run into is that the controls in Me.Controls does not look at nested controls (e.g. a textbox on a panel). In this example, the panel is "seen" but not the textbox inside it.
 
Back
Top